← All notes

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

See also

Claims

Sources

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

Permanent ID: iil:note:pqptwbme

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.},
}

Markdown

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.