Examples in a docstring go stale quietly. Python can run them for you, so a broken example shows up as a failing test.
def to_gb(size_bytes):
"""Convert bytes to whole gigabytes.
>>> to_gb(5_000_000_000)
5
"""
return size_bytes // 1_000_000_000
python -m doctest -v example.py
doctest imports the module and searches the module docstring and all function, class and method docstrings for lines starting with >>>. It runs them and compares the result with the line below. Without -v, it prints nothing unless something fails.
You can also make the file test itself when run directly:
if __name__ == "__main__":
import doctest
doctest.testmod()
For small scripts and helper modules I find this enough testing, and the examples double as documentation that is guaranteed to be right.
Caveats from the docs. The comparison is exact text, so anything whose output varies is fragile: the order of a set, memory addresses in an object’s repr, long floats. Expected output stops at a blank line, so write <BLANKLINE> where you mean an empty line. Output to stderr is not captured. And python -m doctest may not work properly for a file inside a package that imports its own submodules.
Further reading: Python docs: doctest