Python Doctests, Literate Programming, and Org Mode

If you’re a Python programmer and like to have built-in tests for your functions, you probably know about doctest, a way of embedding one or more tests in the docstring of a Python function. Normally, they don’t do anything but if doctest is loaded as the main program or one of doctest’s methods are called, the tests are run and the results are printed to stdout.

John Kitchin likes the idea but found that the nit-picky formatting of the tests was annoying so he didn’t use them very often. Of course, being Kitchin he soon fixed that and in a clever way that leverages Org mode. Rather than fuss with the formatting of the tests, he just put a noweb marker where he wanted the test to be and then included the test as a normal Org mode code block later in the file. He added in a bit of Elisp to reformat the test code so that when the file is tangled it becomes a Python script that can be invoked in the normal way to run the tests.

Kitchin thinks of this as an example of literate programming, which it is, of course, but I prefer to think of it as another example of the power of embedding code in an Org file. The function tests can be run from the Org file to get the expected results for the tests, explanatory text can be added, and when you’re finished you just tangle it to an output file. That file can be invoked as a script to run the tests or imported into another Python file to access the functions in the normal way. Very impressive. Kitchin’s post includes a short video so you can see the system in action and get a better feel for how things work.

This entry was posted in General and tagged , . Bookmark the permalink.