Daniel Keast

Python DocTest

programming, python

Python has a module called doctest in it’s standard library that will search for usage examples in your documentation and check that they work as shown. This means you can copy and paste snippets from the interactive shell, and ensure that they’re kept up to date.

For example, this docstring for a silly add function:

$ cat add.py
def add(x, y):
    """
    >>> add(2, 2)
    4
    """
    return x + y

Can be tested like this:

$ python -m doctest add.py
$

So if you change one without the other:

$ sed -i 's/4/3/' add.py

You’ll get test failures:

$ python -m doctest add.py
**********************************************************************
File "add.py", line 5, in add.add
Failed example:
    add(2, 2)
Expected:
    3
Got:
    4
**********************************************************************
1 items had failures:
   1 of   1 in add.add
***Test Failed*** 1 failures.

This forces you to keep your documentation up to date, and locates your tests next to the code that they’re testing.