Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The issue you're facing is that <code>warnings.warn()</code> calls <code>warnings.showwarning()</code>, which writes the result of <code>warnings.formatwarning()</code> to a file, defaulting to <code>sys.stderr</code>.</p> <p>(See: <a href="http://docs.python.org/library/warnings.html#warnings.showwarning" rel="nofollow noreferrer">http://docs.python.org/library/warnings.html#warnings.showwarning</a>)</p> <p>If you're using Python 2.6, you can use the <code>warnings.catch_warnings()</code> context manager to easily modify how warnings are handled, including temporarily replacing the implementation of <code>warnings.showwarning()</code> to write to <code>sys.stdout</code> instead. That would be the Right Way to handle something like this.</p> <p>(See: <a href="http://docs.python.org/library/warnings.html#available-context-managers" rel="nofollow noreferrer">http://docs.python.org/library/warnings.html#available-context-managers</a>)</p> <p>If you want a quick and dirty hack, throw together a decorator that redirects <code>sys.stderr</code> to <code>sys.stdout</code>:</p> <pre><code>def stderr_to_stdout(func): def wrapper(*args): stderr_bak = sys.stderr sys.stderr = sys.stdout try: return func(*args) finally: sys.stderr = stderr_bak return wrapper </code></pre> <p>Then you can call a decorated function in your doctest:</p> <pre><code>from warnings import warn from utils import stderr_to_stdout class Foo(object): """ Instantiating Foo always gives a warning: &gt;&gt;&gt; @stderr_to_stdout ... def make_me_a_foo(): ... Foo() ... &gt;&gt;&gt; make_me_a_foo() testdocs.py:18: UserWarning: warn("Boo!", UserWarning) &gt;&gt;&gt; """ def __init__(self): warn("Boo!", UserWarning) </code></pre> <p>Which passes:</p> <pre><code>$ python -m doctest testdocs.py -v Trying: @stderr_to_stdout def make_me_a_foo(): Foo() Expecting nothing ok Trying: make_me_a_foo() Expecting: testdocs.py:18: UserWarning: Boo! warn("Boo!", UserWarning) ok [...] 2 passed and 0 failed. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload