doctest finds interactive sessions in docstrings and compares actual output with the recorded output. This keeps short examples from drifting when an implementation changes.
Practical example
def total_with_tax(value: float, rate: float) -> float:
"""Return the total after tax.
>>> total_with_tax(100, 0.2)
120.0
>>> total_with_tax(50, 0)
50.0
"""
return value * (1 + rate)
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
Run the example
The block calls testmod() only when the file runs directly. A project can also run python -m doctest -v file.py. Matching is textual, so representations, whitespace, and decimal places matter.
Where it fits
Use doctests for small contracts, tutorials, and API examples. Avoid burying extensive setup in a docstring. Fixtures, many scenarios, and richer failure reports belong in a conventional test suite.
Practical cautions
Do not record unstable output such as memory addresses or set ordering. Flags such as ELLIPSIS can help, but excessive tolerance may allow an incorrect example to pass.
Keep learning
Strengthen the foundation with unit testing with unittest. The official Python documentation, accessed July 22, 2026, documents the API, limitations, and version differences.