How to let Sphinx autodocument your code

In this article we will look at Sphinx documentation tool and how it can autodocument your code.

Sphinx is a great documentation tool for all sort of languages. But it's mainly used by Python developers. Well site ReadTheDocs hosts almost every Python library documentation and its main intent is usage with Sphinx. But how to write the docs? I mean you can write docs in Sphinx page by page or you can let Sphinx help you a little bit to leverage your documentation in your source code (if you have some).

Sphinx has the ability to read your code and parse pydoc between """ and """ quotes.

This is an example method with some pydoc. For full documentation what and how can be documented please look here.

So let's say you did set up Sphinx project with sphinx-quickstart command and now you are ready to write your project documentation. But how not to monkey write all the documentation when you already have some in your source code? You can include modules/classes/methods/function documentation into your hand written documentation and save some hand typing. Also the logic of keeping technical detail in your code which is included into your main documentation prevents outdated or even missing documentation of new methods.

First of all you need to add sphinx.ext.autodoc into file under extensions list. This unlocks new directives.

Next you need to add your project path to PATH. It's done in file. In the beggining of the file you can see prepared lines sys.path.insert(....). Let's say our project is in the directory app and you whole documentation in docs folder. In such case following lines will do the trick:

In case your project in written in Django framework you need to bootstrap it:

After that you can create a document like:

Which gives you the following autodocumented result:

Use it wisely.