Wednesday, August 26, 2009

ipython and doc tests. Cutting and pasting doctests into your shell.

Doc tests are a kind of literate programming for python. Where you type tests like you're typing stuff into an interpreter. In fact, it's easy to just type stuff into the interpreter and once you've finished playing around, copy the results from your terminal into a test file. This is a great, fairly low effort way of writing tests.

However, what if you have written them in your source code file, and not in the interpreter? Ok, so you've written some doc tests and you want to paste doc tests into your interpreter?

With the normal python interpreter you can't paste doc tests in(I don't think).

However the advanced ipython interpreter can. It has a special mode from writing doc tests. The command is called '%doctest_mode'.

The %doctest_mode command allows you to paste in doc tests, into the interpreter... and have them run. The normal python shell fails at this, as the '>>>' is not valid python syntax. The ipython ignores the '>>>' and the '...' which are normally used for doc tests.

It also changes the ipython prompt to look like the normal python prompt. This is useful for when you're writing doc tests. As the '>>>' is required for doc test.

The other useful command with ipython, to extract the code from your ipython session, to paste back into a file, is the %history command. Using '%history -tn 100' will show you the last 100 lines without any prompt. So then you can just copy/paste your shell session into a text editor.


ipython and %doctest_mode makes writing and reading doctests possible in your shell and your text editor. It makes it a two way process, not a one way process. You can go from your editor into your interpreter... or the other way around from your interpreter into your editor.

The other major use case %doctest_mode allows is to paste examples from documentation, into your interpreter. This is one of the main use cases with doc tests... but the normal python interpreter fails at this. So much documentation uses doc tests these days... so making it easy for people to actually paste that code in is very useful.

Double cheek kiss for ipython!

2 comments:

bcw said...

thank you thank you thank you! I already thought about hacking up django-extensions so that it uses ipython with the "-classic" flag (which also gives you doctype'able output) on "./manage.py shell_plus", but this is so much better!

Just a quick note: in my ipython, the command is called %doctest_mode, not %doctest, but that may be something Ubuntu-specific.

illume said...

Hi,

yeah, oops! Not sure how I didn't get the name of the command right. Maybe because I just type '%doc+tab' all the time :) That's updated now. Thanks.


cu,