python-sphinxdocumentation-generationautodoc

Building TOC in sphinx that reflects project folder structure


I want to autogenerate documentation for a python project. I managed to get a barebones pipeline working with sphinx, but the output is not very pretty and I would appreciate some guidance on how to make the output cleaner and the inputs more maintainable.

My project is organized like so:

docs
   |-- build
   |-- index.rst
   |-- conf.py
app
   |-- main_app.py #entry point that intializes everything, internal imports in .py files are relative to here
   views
      |-- view1.py
      |-- view2.py
      |-- ...
   controllers
      |-- controller1.py
      |-- ...
   models
      |-- model1.py
      |-- ...
   utils
      |-- ...
   plugins
      |-- ...

The table of contents that is generated is flat, like the below:

app
   app.controller.controller1
   app.models.model1
   app.utils.util1
   ...

I would prefer to have a table of contents with several nested levels that reproduces the folder structure of the app folder. How can I modify or redistribute my index.rst (below) to achieve this?

.. automodule:: app.utils.MetaReader
    :members:
...
.. automodule:: app.models.main_model
    :members:
...more automodule statements ...

.. toctree::
   :maxdepth: 4
   :caption: Contents:


Solution

  • I'd put them in docs/api/GROUP_NAME/*.rst, such that it mirrors your API file directory structure.

    In the docs/index.rst you would add a toctree entry for each api/GROUP_NAME/module.rst.

    You can also have index files within each nested folder. You can follow this 2-level deep example: https://github.com/Pylons/pyramid/tree/main/docs/api.