Tut: Easier Tutorial Documentation with Sphinx

The PyCon sessions wound down today, so I’m finally coming up for air. This year I presented Effective Django, which evolved out of last year’s PyCon presentation and my PyOhio 2012 talk. As I prepared my PyCon talk last year, I started building Hieroglyph, which makes it easy to build HTML-based slides using Sphinx. This year I was preparing a different kind of presentation: a tutorial. As I started putting it together, I realized that tutorial-style documents differ from the previous presentations and documentation I’ve written.

In the past I used Sphinx code blocks in my documents, and then used the doctest builder to verify that they were written correctly. With a tutorial, however, I was putting together a demo application, and wanted to include code directly from that. Sphinx has the literalinclude directive, but that wasn’t quite enough: I was using git to manage the sample source repository, so what I really wanted to do was include code from that repository at a particular point in time.

I didn’t want to just copy and paste the code from the Python source into the ReStructured Text files: I did that briefly, and found it difficult to keep in sync as my thinking about the code evolved. I’d copy and paste, write some more text, realize I needed to make a change to the sample code, and then need to go back and change it in two places.

To solve this problem, I wrote Tut. Tut is a Sphinx extension that provides a simple directive, checkpoint. The checkpoint directive switches a git repository to a particular point in time: a branch, tag, or SHA; basically anything you can git checkout.

I used tags for Effective Django, so Tut also includes a script to help manage those. The script installs a post-rewrite hook in your git repository, so that if you need to reorder your commits your tags will be moved to the new SHAs. This can be useful if you find a bug and want to change it (“back in time”), or decide to reorder parts of your tutorial source.

I think Tut is a pretty handy little extension: it allowed me to use Sphinx’s built in inclusion directives in my documents, and eliminated work that took my focus off of actually creating content. You can find it on PyPI, and the source is available on github.

author:Nathan Yergler
tags:sphinx, rst, hieroglyph, tut