Docstrings, comments & types

Python Docstrings: PEP 257 Conventions, Formats and Tools

Docstrings, comments & types · · Published 2026-10-27

A dark grey museum wall label with a printed introduction text about devotional paintings and altarpieces
An introduction label in the Gallery of Old European Painting, National Museum in Warsaw. Photo: BurgererSF, CC0.

A docstring is documentation that travels with the code: it is stored on the object, shown by help() and by editors, and extracted by documentation generators. PEP 257 sets the conventions for writing one. It is short, and it says nothing about markup, which is why several formats coexist.

What makes a string a docstring

PEP 257 defines a docstring as "a string literal that occurs as the first statement in a module, function, class, or method definition". The compiler stores it in the object's __doc__ attribute, which is where help(), IDE tooltips, pydoc and Sphinx's autodoc find it. A string anywhere else in the body is just an expression that is evaluated and discarded.

The conventions PEP 257 sets, written by David Goodger and Guido van Rossum in 2001, are "conventions, not laws or syntax". As the PEP puts it, if you violate them, "the worst you'll get is some dirty looks". PEP 8 relies on it: write docstrings for all public modules, functions, classes and methods; non-public methods can have a comment after the def line instead.

Always use triple double quotes, even for one line, so the docstring can grow later. If it contains backslashes, make it raw: r"""...""".

One-line docstrings

One-liners are "for really obvious cases". PEP 257 lists their properties:

def kos_root():
    """Return the pathname of the KOS root directory."""

Multi-line docstrings

A multi-line docstring is a summary line like a one-liner, followed by a blank line, followed by a longer description. The summary must fit on one line because tools use it on its own, in indexes and tooltips. The closing quotes go on a line by themselves.

def distance(a, b):
    """Return the Euclidean distance between two points.

    Both points are (x, y) tuples of numbers. The result is
    always a float, even for integer coordinates.
    """
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

PEP 257 says what each kind of docstring should cover:

The PEP also asks you not to write argument names in capitals in running text, an old Emacs convention: Python is case-sensitive, and the exact names matter for keyword arguments.

Indentation inside docstrings

A docstring is indented like the code around it, so its raw text contains leading spaces. PEP 257 describes the algorithm tools use to remove them: strip the uniform indentation of the second and later lines, and blank lines at the start and end. The standard library implements it as inspect.cleandoc(). Since Python 3.13, the compiler also strips the common leading whitespace when it stores __doc__; with 3.13, the function above gives:

'Return the Euclidean distance between two points.\n\nBoth points are (x, y) tuples of numbers. The result is\nalways a float, even for integer coordinates.\n'

Markup formats

PEP 257 deliberately says nothing about markup inside docstrings. Three styles are widespread, all readable as plain text:

reStructuredText field lists
The native format of Sphinx, using fields such as :param name:, :returns: and :raises ValueError:.
Google style
Indented sections headed Args:, Returns: and Raises:, popular for its compactness.
NumPy style
Sections with underlined headings such as Parameters and Returns, used across the scientific Python ecosystem.

Sphinx reads the Google and NumPy styles through its bundled sphinx.ext.napoleon extension. Here is the same function in Google style:

def scale(values, factor=1.0):
    """Multiply every value by a factor.

    Args:
        values: An iterable of numbers.
        factor: The multiplier. Defaults to 1.0.

    Returns:
        A new list with the scaled values.

    Raises:
        TypeError: If a value is not a number.
    """
    return [v * factor for v in values]

Pick one style per project. With type hints in the signature, many projects stop repeating types in the docstring and use it for meaning, units and edge cases instead; see our guide to type hints.

Examples that are also tests

A docstring can contain interactive examples, written as a Python session. The standard library's doctest module finds them and checks that the output still matches, so documentation cannot quietly fall out of date:

def double(n):
    """Return twice n.

    >>> double(21)
    42
    """
    return 2 * n

python -m doctest module.py -v runs them; pytest can collect them too with its --doctest-modules option.

Checking docstrings

pycodestyle does not check docstring conventions (only their line length, with the optional W505); its documentation points to pydocstyle. ruff reimplements pydocstyle's checks as D rules. On a small module with a lowercase, single-quoted one-liner and a multi-line docstring missing its blank line, ruff check --select D reported, among others:

geometry.py:5:5: D300 [*] Use triple double quotes `"""`
geometry.py:5:5: D401 First line of docstring should be in imperative mood: "returns the area"
geometry.py:10:5: D205 1 blank line required between summary line and description

Some D rules contradict each other, for example on whether the summary starts on the first or second line, so both tools let you choose a convention (pep257, google or numpy) rather than enabling every rule. Docstrings also matter beyond tools: our article on writing useful comments explains how they divide the work with comments.

Sources