doctest Runs Docstring Examples As Tests

doctest.testmod executes every >>> example in docstrings and compares printed results, turning documentation into tests that catch drift.

PythonData Integrity

Code

pythonsnippet
29 lines
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")

How it works

All of the logic lives in the functions slugify and add_tax.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Entry signature: def slugify(text: str) -> str

slugify is the public entry point; everything else in the file exists to support it.

Key statements

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())

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `doctest`. The file defines `slugify`, `add_tax` at load time.