Sphinx tutorialΒΆ
In this tutorial we will see how to create documentation for a Python project.
Get an overview of Sphinx and reST.
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.
Launch sphinx and configure it.
Take a look at the
docsfolder and check what are those files for.Compile your docs using the
Makefile:make html
and open the build files in your browser.
Add a new
.rstfile in the source directory. For now in can contain only one sentence.Include the file in the
toctreeto make it visible.Warning
The document must contain a title to be included.
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.
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
Add a docstring to the function. If you are using
PyCharmchange the default to Google format:def f(a): """ Multipy by three Args: a (int): integer Returns: int: Three times value """ return a*3
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.
Now that Sphinx has created the
.rstfiles 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
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.
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:
How to link version from your project with the docs version
Using IPython to execute code and show on the output with the ipython directive.
Publish your docs at Read The Docs.