Sphinx tutorialΒΆ

In this tutorial we will see how to create documentation for a Python project.

  1. Get an overview of Sphinx and reST.

  2. Create a new project and add a simple Python script to it:

    def f(a):
       return a*3
    

    We will assume this is our Python project code.

  3. Launch sphinx and configure it.

    Take a look at the docs folder and check what are those files for.

  4. Compile your docs using the Makefile:

    make html
    

    and open the build files in your browser.

  5. Add a new .rst file in the source directory. For now in can contain only one sentence.

    Include the file in the toctree to make it visible.

    Warning

    The document must contain a title to be included.

  6. Play around with the different roles and directives that you can use. Take a look at the code directives.

    Note

    Remember to build your docs to make the changes visible in the HTML output.

  7. Change the configuration file to include the Read the Docs HTML theme.

    Note

    The theme can be installed through conda:

    conda install sphinx_rtd_theme
    
  8. Add a docstring to the function. If you are using PyCharm change the default to Google format:

    def f(a):
        """
        Multipy by three
    
        Args:
            a (int): integer
    
        Returns:
            int: Three times value
    
        """
        return a*3
    
  9. Make you code accessible to Sphinx and generate the docs automatically with sphinx apidocs

    Warning

    Run the command from the main project directory and not from the docs folder, to make your Python scripts accessible.

  10. Now that Sphinx has created the .rst files with your apidocs, add them to your toctree using the modules file.

    Note

    If you have decided to go for the Google docstrings format, add the napoleon extension

  11. Add a module docstring in your script and cross-reference Python objects from the standard library:

    """
    This modules does not import anything from the
    standard library like :obj:`integer <int>`,
    :mod:`os` or :func:`~os.listdir`
    """
    

    Note

    You do not need to rerun the command to generate the apidocs as they read the docstrings directly from the script file.

  12. Add cross reference to other Python libraries using intersphinx:

    """
    :class:`~matplotlib.figure.Figure`
    """
    

Enjoy documenting your projects


There are few items left but they are still interesting: