Hi Pythonistas!
Today I’m sharing a feature that’s built into Python, yet many developers never use it which is doctest.
It makes your docstrings executable. Yes, your documentation becomes your test!
What is doctest?
Doctest lets you write examples in a function’s docstring that Python can automatically run and verify.
A Simple Function with a Doctest
def add(a, b):
"""
Add two numbers.
>>> add(2, 3)
5
>>> add(-1, 1)
0
"""
return a + b
How to Run It
Just add this to your script
if __name__ == "__main__":
import doctest
doctest.testmod()
Then run the script. If all examples pass, you’ll see no output. If one fails, it tells you what went wrong.
Here there will be no output. To check the error case let us change the document string like this an run
def add(a, b):
"""
Add two numbers.
>>> add(2, 3)
5
>>> add(-1, 1)
1
"""
return a + b
Output
**********************************************************************
File "/home/afsal/Desktop/experiments/doctest_example.py", line 7, in __main__.add
Failed example:
add(-1, 1)
Expected:
1
Got:
0
**********************************************************************
1 items had failures:
1 of 2 in __main__.add
***Test Failed*** 1 failures.
Benefits of Using doctest
- Examples double as tests
- Keeps documentation honest
- Great for quick prototyping and educational scripts
- No external tools or frameworks required
When Not to Use It
- For large-scale testing (use unittest or pytest)
- When inputs/outputs are dynamic or non-deterministic
- If tests need setup/teardown logic
Use doctest when:
- You want to add real, tested examples in docstrings
- You're building small scripts or utilities
- You want fast feedback while coding
- Turn your documentation into verification.
I hope you have learned something from this post please share your valuable suggestions with afsal@parseltongue.co.in