Nabeel Ahmed Nabeel Ahmed - 23 days ago 5x
Python Question

Is there way to only perform the doctests, ignoring print function calls?

Hypothetically speaking, my function returns a value and has lot of print statements (maybe 100 or more).

Is there a way to run

such that all the other printing work can be ignored/skipped (I am familiar with the
directive, which is for skipping
examples), i.e. when I execute my function (or run my module as a script) with



python -m doctest

I should get:

  • nothing, in case of success; or

  • error messages in case any test example fails;

and nothing else. Running
should not give me a terminal window full of outputs / text from those
function calls.

Please don't suggest using unit testing (e.g.
) as it'll kill the essence of the question.


doctest uses stdout, not stderr, to show messages from any failing tests. Therefore you cannot patch out stdout as this answer originally suggested - this will suppress your print calls and any messages from doctest.

One option is to define functions that print with an additional 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 print function to the functions that use it, allowing you to pass a NOOP at runtime:

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 print for the whole module under test, for example:

def baz():
    """Does whatever.

        >>> baz()

    print('Hello world')

if __name__ == '__main__':

    import doctest

    print = lambda *args, **kwargs: None


Note that this affects the outputs that doctest sees, too, so you don't include any of the print output in the docstring (I assume this is good news!) It won't work with python -m doctest, though.