Python > Quality and Best Practices > Documentation > Generating Documentation with Sphinx
Sphinx Configuration Example
This snippet demonstrates a basic Sphinx configuration file (conf.py
) for generating documentation for a Python project. It includes essential settings and extensions to get you started with documenting your code. The file contains settings for project information, extensions, and HTML output. The descriptions are written using reStructuredText, a plain text markup syntax. This file acts as the central control point for Sphinx when building your documentation.
Basic Sphinx Configuration (conf.py
)
This code provides a comprehensive example of a Project Information: General Configuration: Options for HTML Output: Extension Configuration:conf.py
file. Let's break down the key sections:
project
: The name of your project.copyright
: The copyright notice.author
: The author of the project.
sys.path.insert(0, os.path.abspath('.'))
: This line is crucial. It ensures that Sphinx can find your project's modules, even if they are not installed in a standard location. It adds the current directory to the Python path.extensions
: A list of Sphinx extensions to enable. Common extensions include:
sphinx.ext.autodoc
: Automatically generates documentation from docstrings.sphinx.ext.napoleon
: Supports Google and NumPy style docstrings.sphinx.ext.doctest
: Runs doctests (examples in docstrings).sphinx.ext.intersphinx
: Links to documentation of other Sphinx projects (e.g., Python standard library).sphinx.ext.todo
: Adds support for 'todo' directives.sphinx.ext.coverage
: Checks documentation coverage.sphinx.ext.mathjax
: Renders math using MathJax.sphinx.ext.ifconfig
: Conditional inclusion of content based on configuration values.sphinx.ext.viewcode
: Adds links to the source code.sphinx.ext.githubpages
: Simplifies publishing to GitHub Pages.templates_path
: Specifies the location of custom templates.exclude_patterns
: Files and directories to exclude from the documentation build.
html_theme
: The HTML theme to use. sphinx_rtd_theme
(Read the Docs theme) is a popular choice. You'll need to install it: pip install sphinx-rtd-theme
.html_static_path
: Specifies the location of static files (e.g., CSS, JavaScript).
intersphinx_mapping
: Configures the intersphinx
extension to link to the Python documentation.todo_include_todos
: Enables the inclusion of 'todo' directives.napoleon_*
: Configure the Napoleon extension for docstring processing. These options control how Google and NumPy style docstrings are interpreted and rendered.
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information ---------------------------------------------------
project = 'My Python Project'
copyright = '2023, Your Name'
author = 'Your Name'
# -- General configuration ---------------------------------------------------
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
# -- Options for todo extension -----------------------------------------------
todo_include_todos = True
# -- Napoleon settings -------------------------------------------------------
napoleon_google_docstring = True
napoleon_numpy_docstring = False
napoleon_include_init_with_doc = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = True
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_preprocess_types = False
napoleon_type_aliases = None
napoleon_attr_annotations = True
Generating Documentation
After configuring conf.py
and creating your reStructuredText files, you can generate the documentation. Navigate to the directory containing your conf.py
file (often a docs
directory) and run the sphinx-build
command from your terminal. This command processes your reStructuredText files and generates the HTML documentation.
# Navigate to your project's root directory (where conf.py is located).
# Then, run the following command:
# sphinx-build -b html ./docs ./docs/_build
# Where:
# -b html specifies the builder (HTML in this case).
# ./docs is the source directory (where conf.py is located, and .rst files containing documentation).
# ./docs/_build is the output directory where the generated HTML files will be placed.
Example reStructuredText (index.rst
)
This is a basic index.rst
file. The toctree
directive creates a table of contents. module1
and module2
would be the names of other reStructuredText files in your docs
directory (without the .rst
extension).
.. toctree::
:maxdepth: 2
module1
module2
Welcome to My Python Project's documentation!
=============================================
This is a sample project documentation.
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Documenting Python Code with Docstrings
This snippet shows how to document a Python function using docstrings. Sphinx (with the Napoleon extension) can automatically extract this information and generate documentation. This example uses a common style with :param:
, :type:
, :raises:
, :returns:
, and :rtype:
tags.
def add(a, b):
"""Add two numbers.
:param a: The first number.
:type a: int
:param b: The second number.
:type b: int
:raises TypeError: If a or b is not an integer.
:returns: The sum of a and b.
:rtype: int
"""
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("Inputs must be integers")
return a + b
Real-Life Use Case
Imagine you are building a complex library for data analysis. You have hundreds of functions and classes, each with specific purposes and parameters. Without documentation, it would be incredibly difficult for other developers (or even yourself after a few months) to understand how to use your library effectively. Sphinx allows you to create comprehensive and easily navigable documentation, making your library much more accessible and maintainable.
Best Practices
sphinx-autogen
to automatically generate documentation from your docstrings.
When to Use Sphinx
Use Sphinx when you need to generate comprehensive, professional-looking documentation for your Python project. It is particularly useful for libraries, frameworks, and any project with a significant amount of code that needs to be understood and used by others.
Alternatives
Pros
Cons
conf.py
file and understanding of various settings.
FAQ
-
Why do I need
sys.path.insert(0, os.path.abspath('.'))
in myconf.py
?
This line tells Sphinx where to find your project's modules. Without it, Sphinx might not be able to import your code and generate documentation from the docstrings. It's essential for projects that are not installed as packages. -
How do I install the Read the Docs theme?
Runpip install sphinx-rtd-theme
in your terminal. -
What is reStructuredText?
reStructuredText (reST) is a plain text markup syntax, similar to Markdown. It is used by Sphinx for writing documentation. While Markdown is more popular, reST offers more features and flexibility for complex documentation projects.