-
Notifications
You must be signed in to change notification settings - Fork 0
Doctest
title: doctest type: language-framework created: 2026-05-16 last_updated: 2026-05-16 related: ["Playradar", "radar/techniques/LambdaUnitTesting"] sources: ["https://hamatti.org/posts/document-intended-usage-through-tests-with-doctest/"] radar_quadrant: Languages & Frameworks radar_ring: Assess radar_position: center
A Python Standard Library module that enables writing executable tests directly inside function docstrings using interactive REPL syntax. Tests double as documentation: they appear in help() output and IDE tooling, and they run as part of the test suite.
Tests are written using the >>> prompt notation inside a docstring. The expected output follows on the next line. The module compares actual output against the expected string exactly.
def reverse(sentence):
"""Reverses provided sentence.
>>> reverse('Hello world!')
'!dlrow olleH'
"""
return sentence[::-1]Execution runs via doctest.testmod() called at module level, or via pytest's --doctest-modules flag without any code changes.
- Tests live next to the implementation — no separate test file needed for simple cases.
- Uses REPL syntax developers already know from interactive Python sessions.
- Each test case can carry a descriptive comment, making docstrings function as worked examples.
- Available in the standard library; no additional dependency.
Literal string matching. Output must match exactly, including whitespace. A stray print() statement for debugging causes test failures. Dictionary or set output with non-deterministic ordering also fails unless handled explicitly.
Complexity ceiling. Functions requiring fixture data, mocks, or complex argument construction produce unwieldy docstrings. At that point a dedicated test file (pytest or unittest) is the better choice.
Doctest suits pure functions with clear input/output relationships: string manipulation, data transformations, calculation utilities. It is the author's position to "choose docstring examples with care... Examples should add genuine value to the documentation." Doctest is not a replacement for a full test suite; it is a complement for functions where the example itself is the best documentation.
pytest discovers and runs doctest examples automatically via --doctest-modules. This allows doctest and pytest-style tests to coexist in the same project without separate runners.
doctest sits in the Assess ring of the Languages & Frameworks quadrant, at center position. Studied via the Hamatti article on 2026-05-16; no personal implementation to date. The module is available in the Python Standard Library with zero setup cost, making a trial straightforward whenever a suitable pure function presents itself. The center position reflects solid understanding without hands-on validation, and the narrow applicable scope (clear-input/output pure functions) reduces urgency relative to broader tools.