Sphinx is a powerful documentation generator that converts reStructuredText (reST) or Markdown source files into various output formats, primarily HTML, PDF, and ePub. While it can document anything, its strength lies in documenting Python projects due to its tight integration with Python's introspection capabilities via the autodoc extension.
How Sphinx Works (Mainly for Python Code)
Here's a breakdown of the typical workflow:
Source Files (reStructuredText/Markdown): You write your documentation in .rst or .md files. These files contain text, headings, lists, links, and special Sphinx directives.
Key for Python: Within these files, you use directives like .. automodule::, .. autoclass::, .. autofunction::, .. automethod:: to tell Sphinx to automatically extract docstrings from your Python code.
Configuration (conf.py): This is a Python file that acts as Sphinx's brain. It tells Sphinx:
Which extensions to use (e.g., sphinx.ext.autodoc for Python docstrings, sphinx.ext.napoleon for Google/NumPy style docstrings, sphinx.ext.viewcode to link to source code).
The project name, author, version.
The HTML theme to use.
Paths to your Python source code so autodoc can find them.
Python Code with Docstrings: Your Python modules, classes, functions, and methods should be well-documented using docstrings (PEP 257). Sphinx's autodoc extension reads these docstrings.
Building the Documentation: You use the sphinx-build command (often via make html) to process your source files.
Sphinx parses the .rst files.
When it encounters an autodoc directive, it imports your Python modules (if configured correctly), inspects them, and extracts the docstrings.
It then renders everything into the desired output format (e.g., HTML pages).
Output (_build/ directory): The generated documentation is placed in a build directory (by default _build). For HTML, this will be a set of static HTML files, CSS, JavaScript, and images that you can open in a web browser.
In essence: You write descriptive text in reST files, mark places where Python docstrings should be inserted, configure Sphinx, and then run a command to generate polished documentation.
Minimal Example
Let's create a very basic Python project and document it with Sphinx.
1. Project Setup:
Create the following directory structure:
code
my_project/
├── src/
│ └── my_module.py
└── docs/
2. Create Python Code (src/my_module.py):
python
# src/my_module.py
def greet(name):
"""
Greets a person by their name.
:param name: The name of the person to greet.
:type name: str
:return: A greeting message.
:rtype: str
"""
return f"Hello, {name}!"
class Calculator:
"""
A simple calculator class.
"""
def add(self, a, b):
"""
Adds two numbers.
:param a: The first number.
:type a: int or float
:param b: The second number.
:type b: int or float
:return: The sum of the two numbers.
:rtype: int or float
"""
return a + b
3. Install Sphinx:
bash
pip install sphinx
4. Initialize Sphinx in the docs directory:
Navigate into your docs directory:
bash
cd my_project/docs
Run the quickstart command:
bash
sphinx-quickstart
You'll be prompted with several questions. For this minimal example, you can generally accept the defaults, but pay attention to these:
Separate source and build directories (y/n)?y (This creates _build and _static, _templates within docs).
Project name:My Awesome Project
Author name(s):Your Name
Project release []:0.1
Project language [en]:en
extension: sphinx.ext.autodoc (y/n)?y (Crucial for documenting Python code)
This will create conf.py, index.rst, Makefile, and make.bat in your docs directory, along with _build, _static, _templates subdirectories.
5. Configure conf.py for autodoc:
Open docs/conf.py. You need to tell Sphinx where to find your Python code. Locate the sys.path section and uncomment/add the following:
python
# docs/conf.py
import os
import sys
sys.path.insert(0, os.path.abspath('../../src')) # This line tells Sphinx where my_module.py is
Also, ensure sphinx.ext.autodoc is in your extensions list:
python
# docs/conf.py
extensions = [
'sphinx.ext.autodoc', # Make sure this is here
]
6. Create a reStructuredText file for your module:
.. _my-module-label:: An internal reference target.
.. automodule:: my_module: Tells Sphinx to document the my_module module.
:members:: Includes all public members (functions, classes, variables) of the module.
:undoc-members:: Includes members even if they don't have docstrings (generally, you want docstrings, but useful for quick setup).
:show-inheritance:: Shows the inheritance hierarchy for classes.
7. Link the new document in index.rst:
Open docs/index.rst and add my_module_docs to the .. toctree:: directive, typically under Contents::
rst
.. toctree::
:maxdepth: 2
:caption: Contents:
my_module_docs # Add this line
8. Build the Documentation:
Make sure you are in the docs directory:
bash
cd my_project/docs
Run the build command:
bash
make html
You should see output indicating Sphinx is building the documentation.
9. View the Output:
After the build completes, open the generated HTML file in your web browser:
bash
# On Linux/macOS
open _build/html/index.html
# On Windows (adjust path if needed)
start _build\html\index.html
You will see the main index.html page, and by clicking on "My Module Documentation", you'll see the automatically generated documentation for greet function and Calculator class, including their docstrings and parameters extracted from your Python code.
This minimal example demonstrates the core principles:
Python Docstrings: Your code is self-documented.
Sphinx autodoc: Reads those docstrings.
conf.py: Configures where to find your code and which extensions to use.
reStructuredText (.rst files): Provides the structure and allows autodoc directives.
Build Process: Generates the final HTML (or other formats).