Python 文档字符串 : inconsistent leading whitespace error without new line

标签 python special-characters docstring doctest

我的文档字符串:

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'

我读过( herehere ),当在文档字符串中使用 \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/

相关文章:

Python,单元测试 : Can one make the TestRunner completely quiet?

相对于彼此的 Python 过滤器列表项

crash - 在python 3 idle中使用特殊字符^或¨使程序崩溃

python - 在 PyDev 中查看函数文档字符串的热键?

python - 分配由 help() 打印的默认值的 pythonic 方法是什么?

python - 如何修复 "List Index Our of Range"错误

python - Tensorflow-GPU 在训练期间保存检查点时卡住了 - 也没有使用整个 GPU,不知道为什么

java - java中是否有任何正则表达式可以仅查找字符串中的转义字符?

python - 如何从 BeautifulSoup 输出中取消转义特殊字符?

Python Docstring : raise vs. 引发