← 中文资源

简体中文版本

doctest 把文档字符串示例变成测试

docstring 里 >>> 形式的示例会被 testmod() 逐条执行并与期望输出比对;文档与行为出现漂移时,示例运行结果会直接暴露差异。

阅读英文原文

实现说明

全部逻辑都在函数 slugify、add_tax中。

使用要点

  • slugify 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 全部导入都来自标准库:doctest。 文件在加载时定义 slugify、add_tax。

签名一览:def slugify(text: str) -> str

核心语句

def add_tax(cents: int) -> int:
    """Add 20% tax, truncating the remainder.
    >>> add_tax(100)
    121
    >>> add_tax(250)
    302
    """
    return cents * 121 // 100
def slugify(text: str) -> str:
    """Lowercase a title and join words with dashes.
    >>> slugify("Release Notes 2026")
    'release-notes-2026'
    >>> slugify("  multiple   spaces  ")
    'multiple-spaces'
    >>> slugify("")
    ''
    """
    return "-".join(text.lower().split())

代码示例

import doctest


def slugify(text: str) -> str:
    """Lowercase a title and join words with dashes.

    >>> slugify("Release Notes 2026")
    'release-notes-2026'
    >>> slugify("  multiple   spaces  ")
    'multiple-spaces'
    >>> slugify("")
    ''
    """
    return "-".join(text.lower().split())


def add_tax(cents: int) -> int:
    """Add 20% tax, truncating the remainder.

    >>> add_tax(100)
    121
    >>> add_tax(250)
    302
    """
    return cents * 121 // 100


results = doctest.testmod()
print(f"{results.attempted} docstring examples ran, {results.failed} failed")