I have the following doctest written x.doctest
:
This is something:
>>> x = 3 + 4
foo bar something else:
>>> from __future__ import division
>>> y = 15
>>> z = int('24')
>>> m = z / y
>>> print (m)
1.6
But when I ran python -m doctest x.doctest
on python 2.7.11, the doctest didn't recognize from __future__ import division
:
**********************************************************************
File "x.doctest", line 11, in x.doctest
Failed example:
print (m)
Expected:
1.6
Got:
1
**********************************************************************
1 items had failures:
1 of 6 in x.doctest
***Test Failed*** 1 failures.
Even when I shifted the future import statement to the first line:
This is something:
>>> from __future__ import division
>>> x = 3 + 4
foo bar something else:
>>> y = 15
>>> z = int('24')
>>> m = z / y
>>> print (m)
1.6
The doctest still fails:
**********************************************************************
File "x.doctest", line 11, in x.doctest
Failed example:
print (m)
Expected:
1.6
Got:
1
**********************************************************************
1 items had failures:
1 of 6 in x.doctest
***Test Failed*** 1 failures.
Why is that so and how can I resolve this?
Is there a flag / option for doctest that asks ensures that from __future__ import division
is recognized?
Note: I could just force the check on print (int(m))
or y = 15.
and the doctest will pass but that is not that desirable.
You can use the option
-Q
for the Python interpreter. Set it tonew
:Get help on Python commandline options with:
Selected output:
More help details here.
Doctests run each line in isolation through the Python compiler. This means that any compiler flags specified with a
from __future__ import ..
statement in the doctest itself is useless in a doctest.However, you can add names from the real
__future__
module to your doctest globals. If you don't use thefrom __future__ import <name>
format but useimport __future__
instead, you import that actual module, and can add references to the objects it defines to the doctestglobs
orextraglobs
dictionaries:The
DocTestRunner
will then set the right compiler flags for you when compiling individual lines from these.Demo: