Chapter 7: Style conventions for functions

Multi-line docstrings

face Josiah Wang

Docstrings can also be written across multiple lines.

Multi-line docstrings starts with a one-line summary just like the one-line docstring. It is then followed by a blank line, and followed by a more elaborate description.

Here is an example taken from PEP 257:

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
    ...

Like one-line docstrings, no blank lines before or after the docstring.

The one-line summary should be just like the one-line docstring, and fit in a single line.

It should be separated from the remainder of the docstring with a blank line.

The remainder of the docstring should be a summary of what the function does and its behaviour. You should also describe its arguments and return values, or anything other assumptions, side effects, etc. If there are optional arguments, mention it.

Note the indentation of the docstring.

The closing triple-quotes should be on a separate line on its own, unless it is a one-line docstring.

The two dominant style of multi-line docstrings are Google style and Numpy style docstrings. Both have their advantages and disadvantages. Just choose one style that best fits your needs and be consistent.

I’ve reproduced both styles from this page.

Google style:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Args:
        arg1 (int): Description of arg1
        arg2 (str): Description of arg2

    Returns:
        bool: Description of return value

    """
    return True

Numpy style:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    """
    return True

Of course, you can also develop your own style. As usual, everything is a guideline, not a hard rule!