【问题标题】:Executing Python doctest code执行 Python doctest 代码
【发布时间】:2015-08-09 17:32:17
【问题描述】:

我有使用文档的简单 Python 代码

#!/usr/bin/python
# http://stackoverflow.com/questions/2708178/python-using-doctests-for-classes

class Test:
    def __init__(self, number):
        self._number=number

    def multiply_by_2(self):
        """
        >>> t.multiply_by_2()
        4
        """
        return self._number*2

if __name__ == "__main__":
    import doctest
    doctest.testmod(extraglobs={'t': Test(2)})

我可以将它与 python 解释器一起使用:

> python simple.py

但是,当我从 doctest 模块执行代码时,我收到此错误:

> python -m doctest simple.py
**********************************************************************
File "simple.py", line 10, in simple.Test.multiply_by_2
Failed example:
    t.multiply_by_2()
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1289, in __run
        compileflags, 1) in test.globs
      File "<doctest simple.Test.multiply_by_2[0]>", line 1, in <module>
        t.multiply_by_2()
    NameError: name 't' is not defined
**********************************************************************
1 items had failures:
   1 of   1 in simple.Test.multiply_by_2
***Test Failed*** 1 failures.

为什么会有这种差异?如何解决这个问题?

【问题讨论】:

    标签: python python-unittest doctest


    【解决方案1】:

    不同之处在于,当您通过doctest 执行时,它是__main__ 模块,而不是直接执行脚本的if __name__ == '__main__' 块将执行的位置。

    除了将您需要的所有信息放入文档字符串本身之外,我不知道有什么好的解决方案:

    def multiply_by_2(self):
        """
        >>> t = Test(2)
        >>> t.multiply_by_2()
        4
        """
        return self._number * 2
    

    这将具有额外的好处,即阅读您的文档字符串的用户将知道发生了什么......他们不必偶然发现您的 extraglobs 关键字来弄清楚 @987654326 是什么@ 是以及它是如何被初始化的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2011-06-23
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多