Import docstrings with Sphinx autodoc¶
Module and function details are useful reference material to have in documentation, but
the process of manually pulling all the necessary details over can become tedious. The
Sphinx autodoc
extension provides
the capability to automatically pull in docstrings and module information for Python
code.
Prerequisites¶
To use the Sphinx autodoc extension with the Sphinx Stack, you need:
Python module files located within the same repository as your documentation
OR
The code repository added as a Git submodule into the documentation repository
Setup¶
In the conf.py file in your docs directory, update the sys.path so that Sphinx can
find your module files. At the top of the file, add a sys.path.insert that adds your
<code> directory:
conf.py¶import sys
from pathlib import Path
relative_code_path = Path('..', '<code>')
absolute_code_path = relative_code_path.resolve()
absolute_code_path_str = str(absolute_code_path)
sys.path.insert(0, absolute_code_path_str) # insert at index 0 so it occurs early in the list
Then, further down in the conf.py file, add sphinx.ext.autodoc to the list of
extensions:
conf.py¶extensions = [
...
"sphinx.ext.autodoc",
]
Usage¶
See Sphinx’s autodoc
instructions
for details.
Known issues and limitations¶
There are a few issues and limitations that should be taken into consideration.
Language¶
The extension’s usage is limited to Python code. There are extensions for some other languages but they have not been tested with the Sphinx Stack, such as sphinxcontrib-rust for Rust.
Docstring format¶
The autodoc extension pulls the docstrings straight into the the reStructuredText
(reST) document, which requires the docstrings to be in reST format. For docstrings in
the Numpy or Google style, the
napoleon
extension can convert the docstrings into reST prior to processing by autodoc.
For documentation that is written in MyST Markdown, wrap the eval-rst directive around
the autodoc calls:
```{eval-rst}
.. py:currentmodule:: code.<module-name>
.. automodule:: <module-name>
:members:
```
Canonical examples¶
Product |
|
Raw Doc |
Rendered Doc |
|---|---|---|---|
Jubilant |
|||
Ops |