Link Search Menu Expand Document

Document Python functions

Code is read more times than it is written. It is important to document it well so that other people can understand it. Although it sounds obvious, the reality is that documenting is something that is done little and poorly.

To document functions, it is important to apply the black box approach. It does not matter what is inside, but what goes in and what comes out.

Simple programs can be documented in the following way. It is not the best way, but it serves the purpose. You will find millions of functions documented this way. It is the simplest.

def add(a, b):
    # Takes two numbers and returns their sum
    return a + b

However, Python offers docstrings (PEP257). A more correct way to document. This is a docstring in a function. It is defined using """. They can also be used in classes, modules, or methods.

def add(a, b):
    """Take two numbers and return their sum."""
    return a + b

Unlike comments with #, the docstrings are accessible at runtime using __doc__.

print(add.__doc__)
# Take two numbers and return their sum

And similarly with help().

help(add)
# Help on function add in module __main__:
#
# add(a, b)
# Takes two numbers and returns their sum

Although the above comment is perfectly valid, if we create more complex functions or develop open source libraries, we may need to include more information.

There are different ways. Google recommends doing it this way. A description of the function, the input arguments with their type, and the output arguments are included.

def add(a, b):
    """
    Returns the sum of two numbers.

    Args:
        a (int, float): The first number to add.
        b (int, float): The second number to add.

    Returns:
        int, float: The sum of a and b.
    """
    return a + b

Another way is according to the reStructuredText format. This allows us to generate documentation automatically with tools like sphinx. Having the documentation next to the code makes it easier to keep it up to date.

def add(a, b):
    """
    Returns the sum of two numbers.

    :param a: The first number to add.
    :type a: int, float
    :param b: The second number to add.
    :type b: int, float
    :return: The sum of a and b.
    :rtype: int, float
    """
    return a + b

Also, numpy has its own way of doing it, and there are dozens of variations. But no matter which one, they all give similar information with different formatting.

As a final note:

  • If you contribute to open source, it is advisable to use English to document your functions. You will be able to reach more people with your packages.
  • Not all functions need 50-line comments following a standard. For simple functions, one line is enough. Choose according to your case.