Sphinx Documentation Generator

raw JSON →
9.1.0 verified Tue May 12 auth: no python install: verified quickstart: stale

Sphinx is a powerful Python documentation generator that creates intelligent and beautiful documentation from reStructuredText or Markdown sources. It is currently at version 9.1.0, with major releases typically annually and patch releases occurring frequently. It leverages Docutils for parsing and processing text, and is highly extensible.

pip install sphinx
error sphinx-build: command not found
cause The `sphinx-build` command is not in the system's PATH, usually because Sphinx was not installed in the active Python environment or its scripts directory is not accessible.
fix
Ensure Sphinx is installed (pip install sphinx) and your virtual environment is activated, or verify that the Python scripts directory containing sphinx-build is included in your system's PATH.
error WARNING: Duplicate label
cause Multiple reStructuredText or Markdown labels with the same name exist across your project, preventing Sphinx from uniquely identifying them for cross-referencing.
fix
Rename duplicate labels in your source files to ensure each label used for internal linking is unique across the entire Sphinx project.
error ModuleNotFoundError: No module named 'sphinx_rtd_theme'
cause The Python package for the specified Sphinx theme or extension (e.g., `sphinx_rtd_theme`) is not installed in the active Python environment where Sphinx is being run.
fix
Install the missing theme or extension package using pip: pip install sphinx_rtd_theme (or the appropriate package name).
error Sphinx error: An exception occurred in conf.py
cause There is a Python error (e.g., syntax error, `NameError`, or incorrect configuration value) within your `conf.py` configuration file, preventing Sphinx from loading its settings.
fix
Examine the full traceback provided after the error message to locate the specific line and nature of the error in conf.py and correct the Python code or configuration value.
error WARNING: autodoc: failed to import module 'your_module_name' from its path
cause Sphinx's `autodoc` extension cannot find the specified Python module because the path to your project's source code is not correctly included in `sys.path` within `conf.py`.
fix
Add the parent directory of your module to sys.path in your conf.py file, typically using import os, sys; sys.path.insert(0, os.path.abspath('.')) or os.path.abspath('../../').
breaking Sphinx 9.1.0 and later no longer support Python 3.11. Projects requiring Sphinx 9.1.0+ must use Python 3.12 or newer.
fix Upgrade your Python environment to 3.12 or higher, or pin your Sphinx dependency to `<9.1.0` if Python 3.11 support is critical.
breaking Sphinx 9.1.0 and later require Docutils 0.21 or newer. Older Docutils versions (e.g., 0.20) are no longer supported.
fix Ensure that `docutils` is updated to version 0.21 or higher. Typically, `pip install sphinx` will handle this automatically, but manual intervention may be needed in environments with locked dependencies.
breaking The `create_source_parser` method in `SphinxComponentRegistry` had its signature changed in Sphinx 9.0.0. It no longer accepts an `app` parameter, but now requires `config` and `env`.
fix Custom Sphinx extensions that override or use `create_source_parser` must update their method signature to accept `config` and `env` parameters instead of `app`.
breaking Starting with Sphinx 9.0.0, non-decodable characters in source files will raise an error, instead of being silently replaced with '?' (as in Sphinx 2.0-8.x).
fix Verify that all source files (e.g., `.rst`, `.md`, `.py` for autodoc) are correctly encoded (typically UTF-8) and do not contain characters that are invalid for their declared encoding.
deprecated The mapping interface (dictionary-like access) for options objects in `sphinx.ext.autodoc` was deprecated in Sphinx 9.0.1. While still functional, it will be removed in a future major version.
fix Refactor code interacting with autodoc options to use attribute access (e.g., `options.key`) rather than dictionary-style access (e.g., `options['key']`) to ensure forward compatibility.
gotcha When using `sphinx.ext.autodoc` to document Python modules, Sphinx needs to be able to import your code. If your modules are not in a standard Python path, Sphinx will report 'module not found' errors.
fix Add the path to your Python project's root directory (or the directory containing the modules to be documented) to `sys.path` within your `conf.py` file, typically using `sys.path.insert(0, os.path.abspath('.'))` or `os.path.abspath('../..')` depending on your `conf.py` location.
gotcha The `sphinx.ext.autodoc` extension underwent a substantial rewrite in Sphinx 9.0.0. While most users should not see changes, extensions interacting with autodoc internals might be affected.
fix If you encounter unexpected behavior or errors with custom extensions and `autodoc`, you can temporarily revert to the legacy implementation by setting `autodoc_use_legacy_class_based = True` in your `conf.py`. Report issues to the Sphinx project.
gotcha Your Python source file contains a `SyntaxError: invalid syntax`, preventing the Python interpreter from parsing your code. This means Sphinx cannot import or process your project's modules.
fix Review the specified line in your Python source file (e.g., `/script.py`, line 26 in the provided output) and correct any syntax errors. Ensure that your Python code is valid and can be executed by the Python interpreter.
breaking The build process failed due to a `SyntaxError` in the user's script (e.g., `script.py`), indicating a malformed Python statement or incorrect string literal declaration. This error occurs within the custom script and is not a direct result of Sphinx or dependency changes.
fix Review the Python code in your script at the indicated line number (e.g., line 24 in `/script.py`) and surrounding lines to correct the syntax error. Ensure all string literals, function calls, and statements are correctly formed according to Python syntax rules. Pay attention to commas, parentheses, and string delimiters.
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 0.52s 92.1M
3.10 alpine (musl) - - 0.50s 91.9M
3.10 slim (glibc) wheel 5.2s 0.39s 93M
3.10 slim (glibc) - - 0.39s 92M
3.11 alpine (musl) wheel - 0.68s 101.3M
3.11 alpine (musl) - - 0.77s 101.0M
3.11 slim (glibc) wheel 5.4s 0.60s 102M
3.11 slim (glibc) - - 0.58s 102M
3.12 alpine (musl) wheel - 0.55s 92.2M
3.12 alpine (musl) - - 0.61s 92.0M
3.12 slim (glibc) wheel 5.1s 0.74s 93M
3.12 slim (glibc) - - 0.78s 92M
3.13 alpine (musl) wheel - 0.53s 92.1M
3.13 alpine (musl) - - 0.56s 91.8M
3.13 slim (glibc) wheel 5.6s 0.59s 93M
3.13 slim (glibc) - - 0.58s 92M
3.9 alpine (musl) wheel - 0.41s 91.4M
3.9 alpine (musl) - - 0.43s 91.3M
3.9 slim (glibc) wheel 6.3s 0.41s 92M
3.9 slim (glibc) - - 0.37s 92M

This quickstart demonstrates how to programmatically build Sphinx documentation for a Python project. It creates a minimal project structure including `conf.py` (configuration), `index.rst` (main document), `my_module.py` (Python code), and `modules.rst` (autodoc entry), then invokes Sphinx to generate HTML output.

import os
import shutil
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace

# Define paths
source_dir = "docs_src"
build_dir = os.path.join(source_dir, "_build")
output_html_dir = os.path.join(build_dir, "html")
doctrees_dir = os.path.join(build_dir, ".doctrees")

# Clean up previous build if exists
if os.path.exists(source_dir):
    shutil.rmtree(source_dir)

# Create source directories
os.makedirs(source_dir)
os.makedirs(os.path.join(source_dir, "_static"))
os.makedirs(os.path.join(source_dir, "_templates"))

# Create a simple Python module to document
module_path = os.path.join(source_dir, "my_module.py")
with open(module_path, "w") as f:
    f.write("""
def greet(name: str) -> str:
    """Greets the given name.

    :param name: The name to greet.
    :type name: str
    :returns: A greeting string.
    :rtype: str
    """
    return f"Hello, {name}!"

class Greeter:
    """A simple greeter class.

    :param greeting_word: The word to use for greeting.
    :type greeting_word: str
    """
    def __init__(self, greeting_word: str = "Hello"):
        self.greeting_word = greeting_word

    def wave(self, name: str) -> str:
        """Waves to the given name.

        :param name: The name to wave to.
        :type name: str
        :returns: A waving greeting.
        :rtype: str
        """
        return f"{self.greeting_word}, {name}! *waves*"
""")

# Create conf.py
conf_path = os.path.join(source_dir, "conf.py")
with open(conf_path, "w") as f:
    f.write("""
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

project = 'My Sphinx Project'
copyright = '2026, My Name'
author = 'My Name'
release = '0.1'

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon', # for Google/NumPy style docstrings
]

html_theme = 'alabaster'
""")

# Create index.rst
index_path = os.path.join(source_dir, "index.rst")
with open(index_path, "w") as f:
    f.write("""
.. _index:

Welcome to My Sphinx Project!
================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

This is a sample project to demonstrate Sphinx documentation.
""")

# Create modules.rst for autodoc
modules_path = os.path.join(source_dir, "modules.rst")
with open(modules_path, "w") as f:
    f.write("""
Module Documentation
====================

.. automodule:: my_module
   :members:
   :undoc-members:
   :show-inheritance:
""")

try:
    # Initialize and build the Sphinx application
    # Use docutils_namespace to ensure clean Docutils state
    with docutils_namespace():
        app = Sphinx(
            sourcedir=source_dir,
            confdir=source_dir,
            outdir=output_html_dir,
            doctreedir=doctrees_dir,
            buildername="html",
            freshenv=True,  # Re-read all files
            warningiserror=False,
            # status=sys.stdout, # Uncomment to see build status in console
            # warning=sys.stderr, # Uncomment to see warnings in console
        )
        app.build(force_all=True)
    print(f"Documentation built successfully in {output_html_dir}")
    print(f"Open file://{os.path.abspath(output_html_dir)}/index.html in your browser.")
except Exception as e:
    print(f"Error building documentation: {e}")
    import traceback
    traceback.print_exc()
finally:
    # Optional: Clean up created files and directories
    # if os.path.exists(source_dir):
    #     shutil.rmtree(source_dir)
    pass