Python doctest - executable examples in docstrings
Answer: doctest finds interactive examples in documentation and checks that they still work. A common use is to check that a module's docstrings are up-to-date. Call doctest.testmod() to run the examples in a module.
Examples
def factorial(n):
"""Return n!. For example:
>>> factorial(5)
120
>>> factorial(0)
1
"""
return 1 if n <= 1 else n * factorial(n - 1)
if __name__ == "__main__":
import doctest
doctest.testmod()
python -m doctest -v mymodule.py
python -m doctest -v README.md # examples in a text file
Rules
- Examples start with a
>>>prompt. Expected output follows until the next prompt or a blank line. python -m doctest -v mymodule.pyruns the same checks from the command line.
See also
Claims
- id: C1 claim: doctest can check that a module's docstrings are up to date. source: S1 evidence: "To check that a module's docstrings are up-to-date"
- id: C2 claim: testmod runs examples in a module. source: S2 evidence: "doctest.testmod()"
- id: C3 claim: Docstrings can hold the examples that doctest runs. source: S1 evidence: "To check that a module's docstrings are up-to-date"
Sources
- [S1] doctest - Test interactive Python examples. Python docs. https://docs.python.org/3/library/doctest.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/doctest.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/doctest.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, doctest - Test interactive Python examples; python/cpython (GitHub), Lib/doctest.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, doctest - Test interactive Python examples; python/cpython (GitHub), Lib/doctest.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python doctest - executable examples in docstrings." iinventedlight Library, iil:note:pqptwbme, version of 2026-11-18. https://iinventedlight.com/library/notes/python-doctest/. License: CC-BY-4.0.
@misc{iil_note_pqptwbme,
author = {{iinventedlight}},
title = {{Python doctest - executable examples in docstrings}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-doctest/},
note = {Permanent ID iil:note:pqptwbme. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-doctest.md.