Verify Documented Examples with doctest
Core idea
doctest recognizes interactive examples written with >>> and expected output in documentation. It executes the example and compares its result with the expected text. DocTestParser can parse a string; DocTestRunner runs the parsed examples. For ordinary modules, doctest.testmod checks examples in docstrings. Keep examples small and deterministic.
import doctestdef box_count(items): return (items + 3) // 4text = '>>> box_count(5)\n2\n>>> box_count(0)\n0\n'test = doctest.DocTestParser().get_doctest( text, {'box_count': box_count}, 'boxes', 'example', 0)r = doctest.DocTestRunner().run(test)print(r.failed, r.attempted)The two documented outputs match the function behavior.
Detect outdated documentation
import doctesttext = '>>> 3 * 4\n11\n'test = doctest.DocTestParser().get_doctest(text, {}, 'demo', 'example', 0)messages = []r = doctest.DocTestRunner().run(test, out=messages.append)print(r.failed, r.attempted)print('Expected:' in ''.join(messages))The deliberate mismatch is captured without displaying variable report formatting.
Common mistake
Do not embed changing timestamps, memory addresses or unordered output as exact expectations. doctest executes examples, so run only trusted documentation; supplement it with explicit unit tests for edge cases.
Practice
Add a documented example for exactly four items and deliberately change its expected value. Inspect the mismatch report and correct it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Doctest
Check your understanding of doctest.
What is printed?
import doctestp=doctest.DocTestParser()print(len(p.get_examples('>>> 2+3\n5\n')))What is printed?
import doctestt=doctest.DocTestParser().get_doctest('>>> 1+1\n2\n',{},'x','x',0)print(doctest.DocTestRunner().run(t).failed)Why avoid timestamps in exact output examples?
Does doctest merely parse documentation?