Hypothetically speaking, my function returns a value and has lot of print statements (maybe 100 or more).
Is there a way to run
python -m doctest mymodule.py
stderr, to show messages from any failing tests. Therefore you cannot patch out
stdout as this answer originally suggested - this will suppress your
One option is to define functions that
verbose parameter, so that you can suppress this when necessary.
def foo(verbose=True): """Does whatever. >>> foo(verbose=False) """ if verbose: print('Hello world')
Although you have to change the functions, this also gives you useful options when not testing.
Another is to explicitly supply the appropriate
def bar(print=print): """Does whatever. >>> bar(print=lambda *args, **kwargs: None) """ print('Hello world')
This also requires changes to function definitions, but at least avoids changes in the bodies of those functions.
A third option is to patch out
def baz(): """Does whatever. >>> baz() """ print('Hello world') if __name__ == '__main__': import doctest print = lambda *args, **kwargs: None doctest.testmod()
Note that this affects the outputs that
doctest sees, too, so you don't include any of the
python -m doctest mymodule.py, though.