Docstrings
|
This section documents the current Python release line as published at the official Python documentation, which is the reference these pages are written and verified against. No specific patch version is pinned. This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. This section’s bibliography lists the reference material consulted while preparing these pages. |
A docstring is Python’s built-in mechanism for attaching documentation to code — a string literal placed
where the language itself will pick it up, retrievable at runtime via .doc or help(), and consumed
both by humans reading the source and by tooling that turns it into browsable documentation.
What Is a Docstring?
A docstring is a string literal that is the first statement in the body of a module, class, function, or
method. PEP 257 sets the conventions every style below builds on: a
one-line docstring fits on a single line, with the closing """ on that same line and no blank line before
or after it; a multi-line docstring opens with a one-line summary, a blank line, then further detail, with
the closing """ on its own line. Full coverage is also in the tutorial’s
Documentation Strings section
(the same source Functions cites for its own brief mention).
"""A module for working with two-dimensional shapes."""
class Circle:
"""A circle defined by its radius."""
def area(self):
"""Return the circle's area."""
return 3.14159 * self.radius ** 2
import shapes
print(shapes.__doc__) # A module for working with two-dimensional shapes.
print(shapes.Circle.__doc__) # A circle defined by its radius.
print(shapes.Circle.area.__doc__) # Return the circle's area.
help(shapes.Circle) # prints a formatted summary built from these docstrings
Documenting Code with Docstrings
A well-documented public function or method’s docstring typically covers, in order: a one-line summary of what it does, its parameters (name, expected type, meaning), its return value, any exceptions it may raise, and, where it helps, a short usage example. Which of these apply depends on the code — a simple helper may need only the summary line, while a public API function benefits from all of them. The style used to lay these out (headings, field markers, indentation) is a separate choice, covered in Docstring Styles below.
An example embedded in a docstring can double as a test: an interactive-session snippet (>>> prompts and
their expected output) inside a docstring can be collected and run automatically via
doctest, keeping the example honest as the code changes.
Docstring Styles
The same function, documented in each of the styles below, to compare them directly:
Google Style
Named sections (Args:, Returns:, Raises:) with indented entries, documented in
the Google Python Style Guide:
def divide(a, b):
"""Divide two numbers.
Args:
a: The dividend.
b: The divisor.
Returns:
The result of a / b.
Raises:
ZeroDivisionError: If b is zero.
"""
return a / b
NumPy Style
Section headers underlined with dashes and a name : type line per parameter, documented in
the numpydoc format guide — the more verbose of the
mainstream styles, and the convention scientific-Python projects (NumPy, SciPy, pandas) use:
def divide(a, b):
"""Divide two numbers.
Parameters
----------
a : float
The dividend.
b : float
The divisor.
Returns
-------
float
The result of a / b.
Raises
------
ZeroDivisionError
If b is zero.
"""
return a / b
reStructuredText (Sphinx) Style
Field lists (:param:, :type:, :returns:, :rtype:, :raises:) inline in the docstring body, the
native format for Sphinx's documentation generator:
def divide(a, b):
"""Divide two numbers.
:param a: The dividend.
:type a: float
:param b: The divisor.
:type b: float
:returns: The result of a / b.
:rtype: float
:raises ZeroDivisionError: If b is zero.
"""
return a / b
Epytext
A legacy style, predating the three above and rarely chosen for new code today, but still found in older
codebases — listed here for completeness. It uses @-prefixed fields (@param, @return, @raise)
similar in spirit to Javadoc:
def divide(a, b):
"""Divide two numbers.
@param a: The dividend.
@type a: float
@param b: The divisor.
@type b: float
@return: The result of a / b.
@rtype: float
@raise ZeroDivisionError: If b is zero.
"""
return a / b
Generating Static Documentation Sites from Docstrings
Docstrings written in any of the styles above can be pulled out of the source and rendered as a browsable documentation site, without hand-writing the reference pages:
Sphinx
Sphinx is the long-standing, most configurable option, and the
generator CPython’s own documentation is built with. Its
autodoc extension pulls docstrings
directly from live, importable code via automodule/autoclass/autofunction directives; its
napoleon extension translates Google-
and NumPy-style docstrings into Sphinx’s native reStructuredText fields, so either style renders correctly
without being rewritten:
pip install sphinx
sphinx-quickstart # scaffolds a docs/ project with conf.py and index.rst
sphinx-build -b html docs docs/_build
pdoc
pdoc is a zero-config alternative: it introspects a package directly and renders its docstrings with no separate build-config file to maintain. Any of the styles above render reasonably; Google and NumPy style render best since pdoc recognizes their section headings:
pip install pdoc
pdoc ./my_package # serves a live-reloading preview; add -o docs to write static HTML instead
MkDocs with mkdocstrings
MkDocs builds a Markdown-based documentation site from a mkdocs.yml config; the
mkdocstrings plugin injects API reference pages pulled from docstrings via
a ::: module.path directive placed in a Markdown page, fitting naturally into a site that already mixes
hand-written guides with generated reference material:
pip install mkdocs "mkdocstrings[python]"
mkdocs serve # live preview at http://127.0.0.1:8000
Sphinx is the most configurable and extension-rich choice, and the long-standing default for large projects
(CPython included); pdoc is the fastest path to a browsable API reference with no configuration at all;
MkDocs with mkdocstrings suits projects that already publish a Markdown-based documentation site and want
API reference pages folded into it alongside hand-written guides.
See Also
-
Functions — the
defstatement itself, and the one-line-docstring form covered briefly there. -
Debugging and Tooling — the adjacent developer-tooling ecosystem (debuggers, profilers, linters and formatters).