How to use docstrings to improve your Python code

Using docstrings in Python makes it easier to see what functions do, what arguments they accept, and what they return. Here’s how to use them.

How to use docstrings to improve your Python code
Picture by Caspar Camille Rubin, Unsplash.
6 minutes to read

Docstrings are comment blocks that are added to the top of Python functions to explain the purpose of the function, describe the arguments that it accepts, and explain what the function returns. Docstrings start on the first line of a Python function and are enclosed in triple quotes, allowing them to span several lines.

Most integrated development environments (IDEs), such as PyCharm and Jupyter, support Docstrings and can display the instructions on using a function within the code editor, avoiding the need for you to visit the package’s website to check the documentation, or view the source to try to decipher it yourself.

Docstring styles

There are several styles for writing docstrings, so you may encounter them in various forms, as well as those which are not really conforming to any specific style guideline. The common docstring formats are: Python Enhancement Proposal or PEP style, Google style, EpyText style, NumPydoc style, and reStructuredText style. PEP, Google and NumPy styles are most commonly used, so I’d be inclined to stick with one of these.

Google docstrings

Google docstrings include the following: a description of the function on the first line; an Args section explaining the type of each argument and what it is used for; a Returns section explaining the type returned; a Raises section explaining any intentional exceptions raised if an error occurs, and a Notes section explaining where to find more information on using the function.

def google_docstring(argument1, argument2=None):
    """The first line describes concisely what the functions does. 
    
    Args: 
        argument1 (str): Description of argument1. If you have lots to say about
            a function you can break to a new line and indent the text so it fits. 
        argument2 (int, optional): Description of argument2. 
    
    Returns: 
        str: Optional description explaining the value returned by the function. 
        
    Raises:
        ValueError: Description of any errors or exceptions intentionally raised. 
    
    Notes: 
        For more information on this function see: https://github.com
    """
    
    pass

NumPy docstrings

A NumPy docstring is fairly similar, and also includes a description of the function on the first line. However, Args is replaced by Parameters, and Returns is replaced by Yields if the function is a generator function.

def numpy_docstring(argument1, argument2=None):
    """The first line describes concisely what the functions does. 
    
    Parameters
    ----------
    argument1 : str
        Description of argument1. 
    argument2 : int, optional
        Description of argument2. 
    
    Returns
    -------
    str
        Optional description explaining the value returned by the function. 
    """
    
    pass

PEP docstrings

PEP docstrings are broadly similar. The first line goes immediately below the function name, is wrapped in triple quotes and ends in a full stop, with a line break beneath. The aim of the docstring is to be used as the “usage” message, so it’s fairly common for these to be quite lengthy. The PEP specifications don’t appear to be as detailed as those for Google or NumPy style docstrings.

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
One-line docstrings

For really obvious examples you still need to comment, you can use a one-line docstring. This still uses triple quotes, as that allows for quick expansion by other developers later on, should end in a full stop (or period), and shouldn’t include any breaks.

"""Here is a one-line docstring."""

Accessing docstrings

When written correctly, a docstring can be used by an IDE and can also be printed, irrespective of the application you’re using for development. To print a docstring you can enter the function name with a .__doc__ suffix. This provides a quick way of accessing function argument information when you’re coding.

print(google_docstring.__doc__)
The first line describes concisely what the functions does. 
    
    Args: 
        argument1 (str): Description of argument1. If you have lots to say about
            a function you can break to a new line and indent the text so it fits. 
        argument2 (int, optional): Description of argument2. 
    
    Returns: 
        str: Optional description explaining the value returned by the function. 
print(numpy_docstring.__doc__)
The first line describes concisely what the functions does. 
    
    Parameters
    ----------
    argument1 : str
        Description of argument1. 
    argument2 : int, optional
        Description of argument2. 
    
    Returns
    -------
    str
        Optional description explaining the value returned by the function. 

Using Inspect to view docstrings

Sometimes you might see another method used for displaying docstrings. The inspect package has some extra features and displays docstrings in a slightly neater manner. You can display docstrings with inspect by passing the function name to the getdoc() function and then printing the output.

import inspect

print(inspect.getdoc(numpy_docstring))
The first line describes concisely what the functions does. 

Parameters
----------
argument1 : str
    Description of argument1. 
argument2 : int, optional
    Description of argument2. 

Returns
-------
str
    Optional description explaining the value returned by the function. 

Matt Clarke, Monday, March 08, 2021

Matt Clarke Matt is a Digital Director who uses data science to help in his work. He has a Master's degree in Internet Retailing (plus two other Master's degrees in different fields) and specialises in the technical side of ecommerce and marketing.

Software Engineering for Data Scientists in Python

Learn all about modularity, documentation, & automated testing to help you solve Data Science problems quicker and more reliably.

Start course for FREE

Comments