Python Tip of the Day: Easy Doctest-ing
In Python you can add a description to any class or function. This description is called a docstring in the Python community.
def addOneToNumber(num):
"""this function adds one to the number parameter passed in.
If not a number will throw InputError"""
if isinstance(num, int) == True:
return num + 1
else:
raise InputError, "Must be a number"
Docstrings document what the function does, just as this docustring does here. Often with a description you want to include an example for future programmers, showing them how to call the function, or what they might expect what happens.
It is a great idea to put examples in your docstrings, but how can you be certain that the examples are up to date? Programmers really hate reading outdated sample code, is there a way to prevent this?
Python provides the doctest module which presents a solution to this problem: docstring will run statements in the docstring, and error if the output is different from what it expected. These docstrings are created by importing your script into a running Python interpreter, running your function, and pasting the command and the results into your docstring.
There’s an easy way to doctest your routines, read on to discover how…