Doctest not recognizing __future__.division

夙愿已清 提交于 2019-12-04 03:28:28

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 the from __future__ import <name> format but use import __future__ instead, you import that actual module, and can add references to the objects it defines to the doctest globs or extraglobs dictionaries:

 if __name__ == "__main__":
     import doctest
     import __future__
     doctest.testmod(extraglobs={'division': __future__.division})

The DocTestRunner will then set the right compiler flags for you when compiling individual lines from these.

Demo:

>>> import doctest
>>> import __future__
>>> import sys
>>> def foo():
...     """
...     >>> 1 / 2
...     0.5
...     """
...
>>> doctest.testmod(sys.modules['__main__'])
**********************************************************************
File "__main__", line 3, in __main__.foo
Failed example:
    1 / 2
Expected:
    0.5
Got:
    0
**********************************************************************
1 items had failures:
   1 of   1 in __main__.foo
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=1)
>>> doctest.testmod(sys.modules['__main__'], extraglobs={'division': __future__.division})
TestResults(failed=0, attempted=1)

You can use the option -Q for the Python interpreter. Set it to new:

python -Qnew -m doctest x.doctest

Get help on Python commandline options with:

python -h

Selected output:

-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew

More help details here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!