Sphinx
Generating Sphinx Docs for Python
Step-by-step guide:
-
Install Sphinx: Install Sphinx in your Python environment using pip.
pip install sphinx
-
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. -
Configure Sphinx: In the
conf.py
file generated bysphinx-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. -
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 inconf.py
:extensions = [ 'sphinx.ext.autodoc', 'myst_parser', ]
-
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 yourconf.py
file. For a module namedmy_module
, the contents ofmy_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. -
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'
-
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 theindex.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
thenmake html
.make docs/html
does not work. - You can use the VsCode Extension live server on the
index.rst
to preview the docs.
Backlinks