While perusing the Python tutorial, I came across a really nifty Python feature that I hadn’t heard about before – namely the doctest module. It’s quite ingenious.
The doctest module provides
a tool for scanning a module and validating tests embedded in a program’s
docstrings. Test construction is as simple as cutting-and-pasting a
typical call along with its results into the docstring. This improves
the documentation by providing the user with an example and it allows the
doctest module to make sure the code remains true to the documentation:
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """ return sum(values, 0.0) / len(values) import doctest doctest.testmod() # automatically validate the embedded tests
This is quite a clever idea as it ensures that your documentation stays up to date. It’s like a unit test for your documentation. Cool, eh?