Sphinx Docstring Format: reST, Google and NumPy Examples
November 11, 2026 · 11 min read
Sphinx Docstring Format: reST Fields, Google and NumPy Styles
A Sphinx docstring is a Python docstring written in reStructuredText, with field lines such as :param width:, :returns: and :raises ValueError:. The sphinx.ext.autodoc extension imports your module and turns those fields into formatted API pages. Turn on the bundled Napoleon extension and Sphinx reads Google and NumPy styles too.
This page writes one function in all three styles and gives you the conf.py that builds them. It also lists the usual reasons a docstring won't render, plus the options for teams who'd rather write Markdown.
What Is the Sphinx Docstring Format?
PEP 257 sets the base rules. A docstring is a string literal that's the first statement in a module, class, function or method. You wrap it in triple double quotes, and a multi-line docstring has a summary line, a blank line, then the body.
Sphinx adds structure on top of that. Its native format is the reST "info field list" from the Python domain: each line starts with a field name between colons, like :param image:. Autodoc pulls the docstring into your docs, Sphinx parses it as reStructuredText, and each field becomes a labeled section in the HTML.
Because the docstring is reST, everything else in reST works inside it too: double-backtick literals, roles such as :class: and :func:, even directives. Docstrings cover the API reference only. Tutorials and how-to pages still need hand-written prose, which our guide to writing documentation in Markdown covers.
Sphinx Docstring Fields: :param:, :type:, :returns: and :raises:
Here's a complete reST-style Sphinx docstring for a small image helper. It uses every field a typical function needs.
def resize(image, width, height=None):
"""Resize an image to a new width, keeping the aspect ratio.
If ``height`` is given, the image is stretched to exactly
``width`` by ``height`` pixels instead.
:param image: The source image.
:type image: PIL.Image.Image
:param int width: Target width in pixels.
:param height: Target height in pixels, or None to keep the ratio.
:type height: int or None
:returns: A new resized image. The original is left unchanged.
:rtype: PIL.Image.Image
:raises ValueError: If width or height is zero or negative.
"""
if width <= 0 or (height is not None and height <= 0):
raise ValueError("width and height must be positive")
if height is None:
height = round(image.height * width / image.width)
return image.resize((width, height))
Sphinx renders this as a Parameters list (each entry shows the name, the type in parentheses and the description), followed by Returns, Return type and Raises blocks. Sphinx links type names when it can resolve them, so int can point to the Python docs if you've set up intersphinx.
These are the fields the Python domain's info field lists recognize:
| Field | Also accepted as | What it documents |
|---|---|---|
:param name: | parameter, arg, argument, key, keyword | One parameter |
:type name: | (none) | The type of that parameter |
:returns: | return | The return value |
:rtype: | (none) | The return type |
:raises Error: | raise, except, exception | An exception and when it's raised |
:var name: | ivar, cvar | A variable or attribute |
:vartype name: | (none) | The type of that variable |
:meta private: | (none) | Hidden metadata, such as marking a member private for autodoc |
A few rules trip people up. Every field needs an argument except :returns: and :rtype:. You can fold a one-word type into the parameter line, as in :param int width:. Separate several types with or or a vertical bar. Finally, :var:, :ivar: and :cvar: render identically, so pick one and use it consistently.
What Does a Python Docstring Example Look Like in Each Style?
Most projects pick one of three styles. Here's the same resize function in Google style, which uses indented sections whose headers end in a colon:
def resize(image, width, height=None):
"""Resize an image to a new width, keeping the aspect ratio.
If ``height`` is given, the image is stretched to exactly
``width`` by ``height`` pixels instead.
Args:
image (PIL.Image.Image): The source image.
width (int): Target width in pixels.
height (int, optional): Target height in pixels. Defaults to
None, which keeps the aspect ratio.
Returns:
PIL.Image.Image: A new resized image. The original is left unchanged.
Raises:
ValueError: If width or height is zero or negative.
"""
And the NumPy version, which underlines each section header with dashes and puts the type after a spaced colon:
def resize(image, width, height=None):
"""Resize an image to a new width, keeping the aspect ratio.
If ``height`` is given, the image is stretched to exactly
``width`` by ``height`` pixels instead.
Parameters
----------
image : PIL.Image.Image
The source image.
width : int
Target width in pixels.
height : int, optional
Target height in pixels. If None, the aspect ratio is kept.
Returns
-------
PIL.Image.Image
A new resized image. The original is left unchanged.
Raises
------
ValueError
If width or height is zero or negative.
"""
The reST version packs each fact onto its own field line. The Google version is the shortest to read in source. NumPy takes the most vertical space but stays legible with ten or more parameters. After Napoleon converts the Google and NumPy versions, all three render essentially the same Parameters, Returns and Raises sections. Both styles have more sections than shown here: a generator uses Yields instead of Returns, a class docstring lists Attributes, and NumPy adds See Also, Notes and Examples.
Turning On Napoleon for Google and NumPy Docstrings
Napoleon has shipped inside Sphinx since version 1.3, so there's nothing extra to install. It's a preprocessor: it rewrites Google and NumPy sections into the reST fields of a native Sphinx docstring before Sphinx parses them. Your source files aren't touched. This conf.py covers a typical src/ layout:
# docs/conf.py
import sys
from pathlib import Path
sys.path.insert(0, str(Path("..", "src").resolve()))
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
]
# Both default to True. Set one to False to switch that style off.
napoleon_google_docstring = True
napoleon_numpy_docstring = True
The sys.path line only matters when you build from a source checkout. If your package is installed in the docs environment (for example with pip install -e .), you can drop it. Our Python project structure guide compares the flat and src layouts.
We prefer Google style for most projects. It reads cleanly as plain source, and it's the least noisy of the three. NumPy style earns its extra lines in scientific code with many parameters and array shapes. Plain reST makes sense when you want no extra extension at all.
Type Hints vs :type: Fields
If your function already has type annotations, repeating the types in the Sphinx docstring means two places to keep in sync. Set autodoc_typehints = "description" in conf.py and autodoc moves the annotations out of the signature and into the field list.
from PIL import Image
def resize(
image: Image.Image, width: int, height: int | None = None
) -> Image.Image:
"""Resize an image to a new width, keeping the aspect ratio.
:param image: The source image.
:param width: Target width in pixels.
:param height: Target height in pixels, or None to keep the ratio.
:returns: A new resized image.
"""
The int | None syntax needs Python 3.10 or later at runtime. With that setting, the rendered page still shows the types next to each parameter and a Return type entry, all taken from the annotations. The other values are "signature" (the default), "both" and "none". If you want finer control over how hints render, the third-party sphinx-autodoc-typehints extension is the usual next step.
Pulling Docstrings into Pages with autodoc and sphinx-apidoc
Docstrings don't appear anywhere until a page asks for them. In an .rst file, the automodule, autoclass and autofunction directives do that:
Image helpers
=============
.. automodule:: imagetools.transform
:members:
:undoc-members:
The :members: option documents the module's public members that have a docstring. Add :undoc-members: to include members without one, and :private-members: for names that start with an underscore. Use .. autofunction:: imagetools.transform.resize when you want a single function on a page.
For a whole package, sphinx-apidoc writes those stub files for you. With conf.py in docs/ as above, run sphinx-apidoc -o docs src/imagetools, then build with sphinx-build -M html docs docs/_build.
Why Are My Docstrings Not Showing Up in Sphinx?
When a Sphinx docstring is missing from the built page, the cause is usually one of these. Work through them in order:
- The import failed. Autodoc imports your module to read it, so an import error means an empty page. Look for an autodoc "failed to import" warning in the build log. Fix it with an editable install, the
sys.pathline above, orautodoc_mock_importsfor heavy dependencies. - The extension isn't loaded.
sphinx.ext.autodoc(andsphinx.ext.napoleonfor Google or NumPy) must appear inextensions. - It isn't really a docstring. The string has to be the first statement in the body. A string after any other statement, or an f-string, leaves
__doc__asNone. - No blank line before the fields. Without it, reST treats
:param width:as part of the paragraph above, so the fields render as running text. - Indentation drifted. Mixed indentation in a field's continuation lines produces "Unexpected indentation" errors and broken lists.
- Napoleon is off. Google or NumPy sections without Napoleon render as plain paragraphs, not as a Parameters list.
- The member was filtered out. No docstring and no
:undoc-members:, or a leading underscore without:private-members:.
Can You Write Python Docstrings in Markdown?
Partly. MyST-Parser lets Sphinx read .md pages (our Markdown vs reStructuredText comparison covers that setup). Docstrings are another matter. The MyST docs note that sphinx.ext.autodoc is hard-coded to generate reST, so inside a MyST page you wrap its directives in an eval-rst block:
```{eval-rst}
.. autofunction:: imagetools.transform.resize
```
That gets the docstring onto a Markdown page, but the docstring itself is still reST. To write the docstring body in Markdown, use sphinx-autodoc2. It analyzes your source statically instead of importing it, and it can parse docstrings as MyST:
# docs/conf.py
extensions = ["autodoc2", "myst_parser"]
autodoc2_packages = ["../src/imagetools"]
autodoc2_docstring_parser_regexes = [
(r".*", "myst"), # parse every docstring as MyST Markdown
]
Outside Sphinx, mkdocstrings is the MkDocs counterpart to autodoc. Its Python handler expects Google style by default and also reads NumPy and Sphinx styles. Our MkDocs Markdown guide walks through the MkDocs side.
One limitation on our end: our Markdown editor previews CommonMark and GitHub Flavored Markdown, not reStructuredText, so fields like :param width: stay as plain text instead of becoming a Parameters list. Check how your docstrings render with a real Sphinx build. To drop a docstring example into a README, the code block generator wraps it in a fenced python block.
A good Sphinx docstring comes down to a summary line, a blank line, and fields that autodoc can parse. Pick reST, Google or NumPy, keep it consistent, and let Napoleon handle the conversion. If an entry goes missing, check the import first, then the blank lines and indentation. For the hand-written pages around your API reference, draft them in the online Markdown editor and watch the preview update as you type.