我的文档字符串:
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: line 6 of the docstring for File.Class.some_f has inconsistent leading whitespace: '2. Another story'
我读过( here 和 here ),当在文档字符串中使用 \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)
预期输出的一部分
关于Python 文档字符串 : inconsistent leading whitespace error without new line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76760704/