Python Function Docstrings

Summary: in this tutorial, you’ll learn about how to use docstrings to add documentation to a function.

Introduction to the help() function #

Python provides a built-in function called help() that allows you to show the documentation of a function.

The following example shows the documentation of the print() function:

help(print)Code language: Python (python)

Try it

Output:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
Code language: Python (python)

Note that you can use the help() function to show the documentation of modules, classes, functions, and keywords. This tutorial focuses on function documentation only.

Using docstrings to document functions #

To document your functions, you can use docstrings. The PEP 257 provides the docstring conventions.

When the first line in the function body is a string, Python will interpret it as a docstring. For example:

def add(a, b):
    "Return the sum of two arguments"
    return a + bCode language: Python (python)

And you can use the help() function to find the documentation of the add() function:

def add(a, b):
    "Return the sum of two arguments"
    return a + b

help(add)Code language: Python (python)

Try it

Output:

add(a, b)
    Return the sum of two argumentsCode language: Python (python)

Typically, you use multi-line docstrings:

def add(a, b):
    """ Add two arguments
    Arguments:
        a: an integer
        b: an integer
    Returns:
        The sum of the two arguments
    """
    return a + b

help(add)Code language: Python (python)

Try it

Output:

add(a, b)
    Add the two arguments
    Arguments:
            a: an integer
            b: an integer
        Returns:
            The sum of the two arguments        Code language: Shell Session (shell)

Python stores the docstrings in the __doc__ property of the function.

The following example shows how to access the __doc__ property of the add() function:

def add(a, b):
    """ Add two arguments
    Arguments:
        a: an integer
        b: an integer
    Returns:
        The sum of the two arguments
    """
    return a + b

print(add.__doc__)Code language: Python (python)

Try it

Summary #

  • Use the help() function to get the documentation of a function.
  • Place a string, either single-line or multi-line strings, as the first line in the function to add documentation to it.

Quiz #

Was this tutorial helpful ?