Doctest和相对进口

时间:2010-10-28 21:16:17

标签: python doctest

我在使用doctest和相对导入时遇到问题。简单的解决方案就是摆脱相对进口。还有其他人吗?

假设我有一个名为example的包,其中包含2个文件:

example/__init__.py

"""
This package is entirely useless.
>>> arnold = Aardvark()
>>> arnold.talk()
I am an aardvark.
"""

from .A import Aardvark

if __name__ == "__main__":
    import doctest
    doctest.testmod()

示例/ A.py

class Aardvark(object):
    def talk(self):
        print("I am an aardvark.")

如果我现在尝试

python example/__init__.py

然后我收到错误

Traceback (most recent call last):
  File "example/__init__.py", line 8, in <module>
    from .A import Aardvark
ValueError: Attempted relative import in non-package

2 个答案:

答案 0 :(得分:12)

创建另一个文件my_doctest_runner.py

if __name__ == "__main__":
    import doctest
    import example
    doctest.testmod(example)

执行my_doctest_runner.py以在example/__init__.py中运行doctests:

$ python2.7 my_doctest_runner.py
**********************************************************************
File "/tmp/example/__init__.py", line 4, in example
Failed example:
    arnold.talk()
Expected:
    I am an aaardvark.
Got:
    I am an aardvark.
**********************************************************************
1 items had failures:
   1 of   2 in example
***Test Failed*** 1 failures.

答案 1 :(得分:0)

只做

from A import Aardvark