Docstrings

FUNCTIONS AND MODULES


What is a Docstring?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes, but two types of extra docstrings may be extracted by tools:

  1. String literals immediately after a simple assignment at the top level are “attribute docstrings”.
  2. String literals immediately after another docstring are “additional docstrings”.

See PEP 258 for a detailed description.

For consistency, always use """triple double quotes""" around docstrings. Use r"""raw triple double quotes""" if you use backslashes.

There are two forms of docstrings: one-liners and multi-line docstrings.

One-line Docstrings

One-liners are for obvious cases. They should fit on one line. Example:

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root
    ...

Notes:

  • Triple quotes are used even for one-liners.
  • Opening and closing quotes are on the same line.
  • No blank line around the docstring.
  • The docstring is a command-style phrase ending in a period.
  • Do not repeat the signature. Do not write:
def function(a, b):
    """function(a, b) -> list"""

Instead use:

def function(a, b):
    """Do X and return a list."""

Multi-line Docstrings

Multi-line docstrings consist of a one-line summary, a blank line, then detailed description. The summary must fit on one line and remain separated by a blank line.

Insert a blank line after docstrings documenting a class. Class methods generally have one blank line between them, so the class docstring must also have spacing.

Script docstrings should work as usage messages and include syntax, environment variables, and files.

Module docstrings should list classes, exceptions, functions, and exported objects with brief summaries. Package docstrings should list exported modules and subpackages.

Function/method docstrings should summarize behavior and document arguments, return values, side effects, exceptions, and restrictions.

Class docstrings should summarize behavior, list public methods and instance variables, and describe subclassing interfaces if relevant.

If a class subclasses another and mostly inherits behavior, the docstring must mention this and summarize differences. Use “override” when replacing a method, and “extend” when calling the superclass method.

Avoid placing argument names in uppercase as done in some Emacs conventions. Argument names must match real keyword argument names. List each argument on its own line. Example:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

If the docstring spans multiple lines, place closing quotes on their own line.

Handling Docstring Indentation

Docstring tools strip uniform indentation from all non-blank lines after the first. Indentation of the first line is ignored. Blank lines at the beginning and end are removed.

Implementation:

def trim(docstring):
    if not docstring:
        return ''
    lines = docstring.expandtabs().splitlines()
    indent = sys.maxsize
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    trimmed = [lines[0].strip()]
    if indent < sys.maxsize:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    return '\n'.join(trimmed)

Docstring Example

The docstring in this example contains two newline characters and is therefore 3 lines long. The first and last lines are blank.

def foo():
    """
    This is the second line of the docstring.
    """

To illustrate:

>>> print(repr(foo.__doc__))
'\n    This is the second line of the docstring.\n    '
>>> foo.__doc__.splitlines()
['', '    This is the second line of the docstring.', '    ']
>>> trim(foo.__doc__)
'This is the second line of the docstring.'

Once trimmed, these docstrings are equivalent:

def foo():
    """A multi-line
    docstring.
    """
def bar():
    """
    A multi-line
    docstring.
    """

Copyright

This document has been placed in the public domain.