Doctest will examine your source code, looking for what appear to be code examples. Any examples it finds, it will test using the Python interpreter and compare its result with the one documented. If they differ, Doctest will let you know.
How does it know what's a code example and what isn't? Well, it expects your examples to be formatted in a particular way. Specifically, it expects examples to resemble what you would see in an interactive interpreter session. You know, like when you type
python with no arguments. I'm talking about this kind of thing:
>>> foo = "bar" >>> list(foo) ['b', 'a', 'r']
If Doctest find the telltale
>>> markers, it'll run the code and check the return values.
How do we use it? One way is to invoke it from within your code, like so:
if __name__ == "__main__": import doctest doctest.testmod()
This will output a doctest report when your code is executed as a script. Another option is to invoke it directly from the command prompt like this:
python -m doctest mymodule.py
Doctest is a kind of testing suite, but it isn't intended to be used as a replacement for your favourite unit testing framework (we have UnitTest or Nose for that). Doctest serves purely to supplement your main code testing by ensuring that your documentation is accurate. Well, the code examples at least.
Its useful for all kinds of code examples too, not just the ones in your source code's docstrings. I find it particularly useful when writing blog posts like this one, for example!