doctest Runs Docstring Examples As Tests
doctest.testmod executes every >>> example in docstrings and compares printed results, turning documentation into tests that catch drift.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.