How can I make my (Python 2.7) code aware whether it is running in a doctest?
The scenario is as follows: I have a function that print()s some output to a file descriptor passed in as an argument, something like this:
from __future__ import print_function
def printing_func(inarg, file=sys.stdout):
# (do some stuff...)
print(result, file=file)
But when I try to use printing_func() in a doctest, the test fails; because of my specification of the keyword argument file when invoking print(), the output actually goes to sys.stdout rather than whatever default output redirection is set by the doctest module, and doctest never sees the output.
So how can I make printing_func() aware whether it is running inside a doctest, so that it knows not to pass the file keyword argument when calling print()?
I figured out the answer after reading
doctest.py; posting here for posterity…Doctest redirects standard output by assigning a new file descriptor to
sys.stdout. The problem was that my function description was closing over the value of the originalsys.stdoutfile descriptor prior to doctest’s redefinition.Instead, if I do the following:
then
printing_func()will capture thesysmodule rather thansys.stdout, and when it runs it will retrieve doctest’s redefinedstdoutattribute fromsysif running inside a test.EDIT: This also yields an easy way to check whether we are running inside a doctest: