Docstring formats are standardized ways to write documentation strings in Python — they make code self-documenting, enable automatic generation of API references (via Sphinx, mkdocs, pydoc), improve IDE tooltips/hover help, and support type checkers (mypy, pyright) and testing tools (doctest). In 2026, the three dominant formats remain Google Style (clean and readable), NumPy/SciPy Style (detailed and scientific), and reStructuredText (reST) Style (Sphinx-native, powerful for complex docs). Choosing a format depends on your project: Google for simplicity and Google-style projects, NumPy for scientific libraries, reST for Sphinx-heavy documentation. Consistency across a codebase is key — pick one and stick to it.
Here’s a complete, practical guide to the three main docstring formats in Python: Google, NumPy/SciPy, and reST styles — structure, sections, examples, when to use each, and modern best practices with type hints, doctests, Sphinx integration, and pandas/Polars usage.
Google Style — clean, readable, widely adopted (Google, TensorFlow, many open-source projects) — uses section headers like “Args”, “Returns”, “Raises”, “Examples” with indented descriptions.
def divide(dividend: float, divisor: float) -> float:
"""Divide two numbers.
Args:
dividend (float): The number to be divided.
divisor (float): The number to divide by.
Returns:
float: The quotient of the division.
Raises:
ZeroDivisionError: If divisor is zero.
Examples:
>>> divide(10, 2)
5.0
>>> divide(7, 0)
Traceback (most recent call last):
...
ZeroDivisionError: Cannot divide by zero
"""
if divisor == 0:
raise ZeroDivisionError("Cannot divide by zero")
return dividend / divisor
NumPy/SciPy Style — detailed, structured, scientific-community favorite — uses “Parameters”, “Returns”, “Raises”, “Notes”, “Examples” with type/parameter descriptions aligned in a table-like format.
def gaussian(x: float, mu: float, sigma: float) -> float:
"""Calculate the value of a Gaussian distribution at point x.
Parameters
----------
x : float
The point at which to evaluate the Gaussian distribution.
mu : float
The mean of the distribution.
sigma : float
The standard deviation of the distribution.
Returns
-------
float
The value of the Gaussian distribution at point x.
Raises
------
ValueError
If sigma is not positive.
Notes
-----
The Gaussian distribution is given by:
.. math::
f(x) = \\frac{1}{\\sigma \\sqrt{2 \\pi}} \\exp\\left(-\\frac{(x - \\mu)^2}{2 \\sigma^2}\\right)
"""
if sigma <= 0:
raise ValueError("sigma must be positive")
return (1 / (sigma * np.sqrt(2 * np.pi))) * np.exp(-((x - mu) ** 2) / (2 * sigma ** 2))
reStructuredText (reST) Style — Sphinx-native, verbose, powerful for complex docs — uses “:param:”, “:type:”, “:returns:”, “:raises:” field lists and supports directives (math, code blocks, examples).
def fibonacci(n: int) -> int:
"""Compute the nth Fibonacci number.
:param n: The index of the Fibonacci number to compute.
:type n: int
:returns: The nth Fibonacci number.
:rtype: int
:raises ValueError: If n is negative.
**Examples**:
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
"""
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
Real-world pattern: docstrings in pandas/Polars-style code — use NumPy style for scientific/numerical functions, Google style for general utilities, reST for Sphinx-generated API docs.
# NumPy style for data processing function
def normalize_series(s: pd.Series) -> pd.Series:
"""Normalize a pandas Series to zero mean and unit variance.
Parameters
----------
s : pd.Series
Input series to normalize.
Returns
-------
pd.Series
Normalized series with zero mean and unit variance.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4, 5])
>>> normalize_series(s)
0 -1.414214
1 -0.707107
...
"""
return (s - s.mean()) / s.std()
Best practices for docstring formats make documentation consistent and useful. Choose one format per project — Google for simplicity/readability, NumPy for scientific code, reST for Sphinx-heavy projects. Include summary line (one sentence), Args/Parameters, Returns, Raises, Examples (doctests for testing). Modern tip: use Polars/pandas docstrings in NumPy style — enables ?function in Jupyter and Sphinx autodoc. Add type hints in signature — def func(a: int) -> str — reduces duplication in docstring. Run doctests — python -m doctest file.py — ensures examples are correct. Use tools like pydocstyle, flake8-docstrings — enforce style/consistency. Generate docs with Sphinx — use sphinx-apidoc + autodoc for API reference. Keep docstrings concise but complete — avoid repeating function name/signature. Use :meta: or .. note:: for additional info. Combine with ItemLoader in Scrapy — document item fields in class docstring.
Docstring formats — Google, NumPy/SciPy, reST — standardize how we document functions/classes/modules. In 2026, pick one per project, include summary/Args/Returns/Raises/Examples, use type hints in signature, run doctests, and generate Sphinx docs. Master docstring formats, and your code becomes self-explanatory, testable, and ready for API documentation and IDE support.
Next time you write a function — document it properly. It’s Python’s cleanest way to say: “Here’s what I do, how to use me, and what to expect.”