Doctests (from Python’s built-in doctest module) let you embed interactive Python session examples inside docstrings. When you run doctest.testmod(), Python executes those examples and verifies they still produce the expected output. This turns your docstrings into both documentation and automated tests — a powerful form of “literate testing” or “executable documentation.”
In this up-to-date 2025–2026 guide, you’ll master how to write doctests in Python: basic syntax, multi-example tests, edge cases, verbose mode, integration with functions/classes/modules, best practices, common pitfalls, and modern tools to supercharge your workflow.
Key Takeaways – How to Write Doctests in Python
- Write doctests in Python inside triple-quoted docstrings (“””) right after function/class/module definitions.
- Format: >>> prompt + code + expected output — exactly like interactive Python shell.
- Run tests automatically with doctest.testmod() in if __name__ == “__main__”:.
- Use -v flag (python -m doctest -v file.py) for verbose output showing every test.
- Doctests catch regressions, document behaviour, and serve as executable examples.
- Great for edge cases, error handling, and showing real usage patterns.
- Combine with pytest + pytest –doctest-modules for even more power.
- Avoid over-testing obvious code — focus on non-trivial behaviour.
Prerequisites
- Python 3.8+ (examples tested on 3.10–3.13)
- Text editor or IDE (VS Code with Python extension recommended)
- Basic Python knowledge (functions, docstrings, modules)
Step 1: Basic Doctest Syntax
How to write doctests in Python is simple — place them inside the docstring of a function/class/module.
Example – simple addition function:
def add(a, b):
"""
Add two numbers and return the result.
>>> add(2, 3)
5
>>> add(-1, 1)
0
>>> add(0, 0)
0
"""
return a + b
Run the tests:
if __name__ == "__main__":
import doctest
doctest.testmod()
Or from terminal (verbose mode):
python -m doctest -v add.py
Output shows every test passed:
Trying:
add(2, 3)
Expecting:
5
ok
Trying:
add(-1, 1)
Expecting:
0
ok
...
1 items passed all tests:
3 tests in add.add
3 tests in 1 items.
3 passed and 0 failed.
Test passed.
Step 2: Writing Multi-Line & Complex Doctests
Write doctests in Python for multi-line code, loops, conditionals, exceptions — just like real interactive sessions.
Example – vowel counter with edge cases:
def count_vowels(word):
"""
Count vowels (a,e,i,o,u) in a word, case-insensitive.
>>> count_vowels('hello')
2
>>> count_vowels('AEIOU')
5
>>> count_vowels('rhythm')
0
>>> count_vowels('')
0
>>> count_vowels('Cryptocurrency')
4
"""
return sum(1 for char in word.lower() if char in 'aeiou')
Test exceptions:
def divide(a, b):
"""
Divide a by b.
>>> divide(10, 2)
5.0
>>> divide(5, 0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
"""
return a / b
Step 3: Doctests for Classes & Modules
Write doctests in Python for classes and entire modules — place them at the top of the file or in class docstrings.
Module-level doctest:
"""
Module-level examples:
>>> 2 + 2
4
>>> import math
>>> math.sqrt(16)
4.0
"""
class Calculator:
"""
Simple calculator class.
>>> calc = Calculator()
>>> calc.add(5, 3)
8
>>> calc.subtract(10, 4)
6
"""
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
Step 4: Run Doctests Automatically & Verbose Mode
Best practice – always include in __main__:
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) # Shows every test
Command-line options:
# Run all doctests in a file
python -m doctest -v myfile.py
# Run only doctests (ignore main code)
python -m doctest myfile.py
# Show failures only
python -m doctest myfile.py -v | grep -i fail
Step 5: Best Practices & Modern Tips (2025–2026)
- Explain intent — focus on why, edge cases, and real usage (not obvious code).
- Keep tests minimal — 2–5 examples per function; cover happy path + edges + errors.
- Use pytest integration:
pytest --doctest-modules
Combines doctests with pytest’s power (fixtures, markers, coverage).
- Format with black + ruff — keep docstrings clean and PEP-257 compliant.
- Tools that help write doctests:
- VS Code + Pylance → auto-generate docstring templates
- doctest + pytest-doctest → run in CI
- xdoctest → faster, better reporting (pip install xdoctest)
- Avoid:
- Floating-point exact matches (>>> 1/3 → 0.333… fails)
- Non-deterministic output (random, dates)
- Overly long examples
How to Write Doctests in Python – FAQ (2025–2026)
- How do I write doctests in Python?
Embed >>> examples inside “”” docstrings — simplest way to write doctests in Python. - How do I run doctests in Python?
import doctest; doctest.testmod() or python -m doctest -v file.py. - Can I write doctests for classes in Python?
Yes — place in class docstring or module-level — powerful way to write doctests in Python. - What’s the difference between doctest and unittest/pytest?
Doctest = executable doc examples; pytest/unittest = structured unit tests. Use both! - How do I handle exceptions in doctests in Python?
Write the full traceback — doctest checks it matches exactly.
Summary
You now know exactly how to write doctests in Python: embed interactive examples in docstrings, run with doctest.testmod(), handle multi-line code, test edge cases/exceptions, integrate with pytest, and follow modern best practices.
Doctests make your code self-documenting, self-testing, and trustworthy — a superpower for clean, maintainable Python projects.
Recommended Next Steps
- Python Docstrings & PEP 257/287
- pytest + doctest Integration
- xdoctest – Faster Doctest Runner
- Type Hints + Doctests (Python 3.12+)
- Build a Small Project with Full Doctests