You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python doctest报不一致前导空格错误,如何非缩进解决?

问题原因

doctest 会按缩进层次解析 docstring 里的内容:连续的、同缩进的 >>> 测试代码和关联文本会被视为一个测试块。你的代码里,2. Another story 和第一个故事标题缩进一致,但它紧跟在更深缩进的测试代码之后,doctest 会误以为这行是测试块的一部分,因此抛出缩进不一致的错误。

解决方法

最直接且不改变你排版需求的方式,是在两个故事之间加一个空白行,分隔开测试块和后续文本块,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 注释(用 # 开头),这样 doctest 会忽略该行,也能避免缩进问题,但会改变原文本的呈现样式:

def some_f():
    """
    1. First story
        >>> str(5)
        # if you want to see the value:
        >>> print(str(5))
    2. Another story
        bla bla
    """

内容的提问来源于stack exchange,提问作者Piotr Wasilewicz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 07:47:08