Sphinx and autodoc

Posted on

It’s always a good idea to add some comments to a code, especially when you have several functions or classes with a small API. It’s even better if you are using docstrings (when it comes to Python of course). Unfortunately, the integration in Sphinx documentation system isn’t automatic and requires a bit of work. Nothing fancy but it’s always good to keep a trace of it.

When it comes to create a program or package in Python, I would always recommend to use a cookie cutter to save some time and avoid the pain of writing everything by hand which is painful. For this, there is the excellent package produced by Audrey Roy Greenfeld. If you do so, Sphinx will be part of your requirements_dev.txt otherwise don’t forget to install it.

In order to use autodoc, you will have to ensure that its enabled in the conf.py file with the line:

extensions = ['sphinx.ext.autodoc']

In this file, you will need to tell Sphinx where are located your source files by uncommenting the following line:

sys.path.insert(0, os.path.abspath('.'))

You will have to adapt the path to your needs. If you used cookiecutter, it should be something like ../<package-name>. Now that we are done with the configuration, the second step is the most tedious and hated by programmers, writing the documentation. Write you docstrings wherever you feel relevant. I would suggest eventually to use the Google format which is quite clear and available through the Napoleon package.

From that point, you can generate the documentation either by manually entering the files in a api.rst (don’t forget to add this file to the index.rst toc) file for example such as:

..automodule:: mypackage.mymodule

..autoclass:: myclass
  :exclude-members: __weakref__

It will be very tedious if you have an important code base. Another possibility being using a tool provided by Sphinx, the apidoc. This command-line tool generates directly the ReSTructured files according to the docstrings in your source code. In order to proceed you just have to use the following command:

sphinx-apidoc -f -o <source-doc-dir> ../<package-source>

Be careful with the paths, I suppose here that you are running the command inside your documentation folder. If you use the cookiecutter package, the <source-doc-dir> will be ., if you used sphinx-quickstart and didn’t touch the default parameters it should be source. The -f parameter is used to rewrite the files as Sphinx don’t overwrite the files and this will be a problem if you want to update your documentation. For the other parameters, you should specify the relative path to the source files. If everything worked as expected you should see at least two files names <package.rst> and modules.rst. Just add the former to the TOC of your documentation and run a compilation.

Eventually, if you don’t want to run the sphinx-apidoc every time, you will need to add it to the Makefile.