Sphinx Documentation Generator
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.
Warnings
- 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.
- breaking Sphinx 9.1.0 and later require Docutils 0.21 or newer. Older Docutils versions (e.g., 0.20) are no longer supported.
- 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`.
- 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).
- 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.
- 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.
- 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.
Install
-
pip install sphinx
Imports
- Sphinx
from sphinx.application import Sphinx
- main (sphinx-build)
from sphinx.cmd.build import main
Quickstart
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