Sphinx

Generating Sphinx Docs for Python

Step-by-step guide:

  1. Install Sphinx: Install Sphinx in your Python environment using pip.

    pip install sphinx
    
  2. Initialize the docs directory: Run sphinx-quickstart in your project directory to generate the base files for the documentation.

    mkdir docs
    cd docs
    sphinx-quickstart
    

    When prompted, you can press enter to accept the default values for most options. Make sure to say yes (y) to the "autodoc" extension, which is used to generate documentation from docstrings.

  3. Configure Sphinx: In the conf.py file generated by sphinx-quickstart, add the path to your project to the system path.

    import os
    import sys
    sys.path.insert(0, os.path.abspath('../src'))
    

    Also, add 'sphinx.ext.autodoc' to the list of extensions.

  4. Install and Configure the MyST parser: If you want to use Markdown for some or all of your documentation, you'll need to install the MyST parser and add it to your list of extensions:

    pip install myst-parser
    

    Then add it to the extensions list in conf.py:

    extensions = [
        'sphinx.ext.autodoc',
        'myst_parser',
    ]
    
  5. Write reStructuredText and Markdown files: Create .rst and/or .md files for each of your modules to tell Sphinx what to document. These files should be in the same directory as your conf.py file. For a module named my_module, the contents of my_module.rst could be:

    my_package.my_module module
    ==========================
    
    .. automodule:: my_package.my_module
       :members:
    

    Update the index.rst file to include your module in the table of contents tree (toctree).

    To link to other documentation files, use the :doc: role in reStructuredText files and standard Markdown links in Markdown files.

  6. Install and configure a theme: To use the "Read the Docs" theme, first install it with pip:

    pip install sphinx_rtd_theme
    

    Then, add it to the list of extensions and set it as the theme in conf.py:

    extensions = [
        'sphinx.ext.autodoc',
        'sphinx_rtd_theme',
        'myst_parser',  # if you're using Markdown
    ]
    html_theme = 'sphinx_rtd_theme'
    
  7. Generate the HTML documentation: Now you can generate the HTML documentation with the make html command.

    make html
    

    If everything is set up correctly, Sphinx should generate the documentation in the _build/html directory. Open the index.html file in a web browser to view your documentation.

Remember that every time you update your code or .rst/.md files, you should re-run make html to update the HTML documentation.

Additional Notes and Gotchas

  • Standard practice is to keep docs outside of src.
  • You must cd to docs dir to make html cd docs then make html. make docs/html does not work.
  • You can use the VsCode Extension live server on the index.rst to preview the docs.

Backlinks