Sphinx: Scratching the Surface of Its Power

As I explained in a previous post, Sphinx generates standard html documentation using the file index.rst as its master document. Here I will describe the things you can add to this file to make your documentation better.

Main structure of index.rst
The file index.rst comes with the following lines:
.. toctree::
…….:maxdepth: 2

If all you intend to do is have Sphinx generate documentation by reading the docstrings of a Python module, then do not modify these lines. Also, anything that you add to index.rst should be below these lines.

Now, to have Sphinx generate documentation using a module’s docstrings, say astrotools,  just add the following lines to index.rst:
.. automodule:: astrotools
…….:members:

Adding images
To add an image at the beginning of your html documentation, add the following lines to index.rst:
.. image:: image.jpg
…….:height: 200px
…….:width: 200px
…….:align: left

If you do not provide a full path with the image file, Sphinx will assume that image.jpg resides in the current folder.

Adding external links
One way to add clickable external links to parts of your documentation is to use “external link markers”. Let’s say that in one of the docstrings of your module you have the word “CNN”, and you want to add to it a link to CNN’s website. This is what you do:
Step 1:
In the project’s index.rst file, add the “external link marker”:
.. _CNN: http://www.cnn.com

Step 2:
In your module docstring, write the word as: ‘CNN’_

Adding special characters
Sphinx does not recognize special ascii characters, and so if you write them directly in your docstrings, Sphinx will not include them in its html output. Instead, use “substitutions” and the unicode descriptors of those special characters.

Let’s say that in one of the docstrings of your module, you want to write the word “Núñez”. This is what you do:
Step 1:
In the project’s index.rst file, add the following two “substitutions”:
.. |uacute| unicode:: 0x00FA
…….:trim:
.. |ntilde| unicode:: 0x00F1
…….:trim:

Step 2:
In your module docstring, write the word as: ‘N |uacute| |ntilde| ez’

To learn how to do other fun things to your Sphinx documentation, please refer to Sphinx’s documentation online.

Leave a Reply

Your email address will not be published. Required fields are marked *