我的文档字符串:
def some_f():
"""
1. First story
>>> str(5)
if you want to see the value:
>>> print(str(5))
2. Another story
bla bla
"""
使用 doctest 时,我得到:
ValueError:File.Class.some_f 文档字符串的第 6 行具有不一致的前导空格:'2。另一个故事'
\n
或其他特殊字符时可能会出现此问题,但这里不是这种情况。不知道为什么会发生这种情况以及如何解决这个问题。事实上,它希望我将第二个点移到右侧,因为它工作正常:
def some_f():
"""
1. First story
>>> str(5)
if you want to see the value:
>>> print(str(5))
2. Another story
bla bla
"""
但这不是我想要的。
问题和标题应包括说明此错误是因为您正在运行而发生的
doctest.testmod()
;否则 Python 不关心你的格式。
问题在于 doctest 期望每行看似交互式提示的行后面都跟着 doctest 的预期输出,并且它认为空行或其他
>>>
的出现是预期结果的结尾。
留一个空行来显示预期输出的结尾,并且它不会关心下一行的空格。
def some_f():
"""
1. First story
>>> str(5)
'5'
if you want to see the value:
>>> print(str(5))
5
2. Another story
bla bla
"""
pass
if __name__ == '__main__':
import doctest
doctest.testmod()
如果
'5'
之后没有换行符,这种情况将会失败,因为 doctest 将包含 if you want to see the value:
作为 >>>str(5)
的预期输出的一部分