Skip to content

Sphinx - Read the Docs documentation

G. Iadarola and R. De Maria

For python packages, we found particularly convenient to use sphinx to document the code and to host the documentation on Read the Docs. The API documentation can be generated by sphinx from the docstrings in the code.

The main steps to create a sphinx-rtd documentation are the following:

Install sphinx and rtd-theme

  • Install sphinx and the rdt-theme:
    $ pip install sphinx
    $ pip install sphinx-rtd-theme
    

Start documentation pages

  • The code to be documented needs to be hosted in a GitHub or GitLab account
  • Add requirements.txt to your repository. In order to get documentation from the docstrings, Read the Docs will need to import your python package in a python virtual environment. It will install the dependencies based on the requirements file, which simply consists in the list of packages that need to be installed. For example:
    numpy
    scipy
    
  • Create a docs folder inside your repository and populate it, for example with these example files.
  • Edit conf.py to add to the python path the folder containing the python package to be documented (sphinx needs to import the package to access the docstrings).:
    import sys
    sys.path.insert(0, os.path.abspath('../')) # path relative to conf.py
    
    Many other customizations are possible using conf.py.
  • Compile your project locally by typing:

    $ make html
    
    This generates a simple preview of your documentation (less advanced than rtd) in the folder _build. You can open _build/index.html in your browser to navigate the preview.

  • Add .readthedocs.yaml to your repository. To configure Read the Docs, you will need to include a file like below.

# Read the Docs configuration file for Sphinx projects
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the OS, Python version and other tools you might need
build:
  os: ubuntu-22.04
  tools:
    python: "3.11"

# Build documentation in the "docs/" directory with Sphinx
sphinx:
   configuration: docs/conf.py

# Specify the requirements file
python:
   install:
   - requirements: requirements.txt

On readthedocs.org

  • Create an account on https://readthedocs.org (the easiest is to link it to your github account), it you don't already have one.
  • Add a project linked to your GitHub/GitLab repository.
  • Add .readthedocs.yaml by specifying .readthedocs.yaml under Admin > Advanced Settings -> Path for .readthedocs.yaml.

Edit your documentation

A lot of information about the RST format used in the documentation and about the sphinx doc generation can be found in these tutorials:

An example of documentation from our team can be found at: