Skip to content

Python docstrings

How to write Python docstrings for functions, classes, modules, and scripts using single-line and multi-line formats with PEP 257 conventions.

Python docstrings

Python docstrings are the string literals that appear immediately after the definition of a function, method, class, or module.

For example:

def sum(a, b):
    '''Takes in two numbers, returns their sum'''
    return a+b

where the string literal of the sum() function is

'''Takes in a number n, returns the square of n'''

Python Comments vs Docstrings

Python Comments

Comments are essential when writing a program because they describe what happens inside a program.

They are completely ignored by the Python interpreter.

In Python, the symbol # is used to write a single-line comment.

For example:

print("Hello World") 

Python Comments Using Strings

If you do not assign strings to any variables, they serve as comments.

"This is a single-line comment"

'''
This is a
multi-line 
comment
'''

print("Hello World")

Python docstrings

Python docstrings are strings used immediately after the definition of a function, method, class, or module to document the code.

Python docstrings can be accessed using the __doc__ attribute.

Python __doc__ attribute

Whenever string literals are present immediately after the definition of a function, module, class, or method, they are associated with the object as the __doc__ attribute.

In this way, string literals can be retrieved using the __doc__ attribute.

For example, the documentation of our sum() function can be accessed using the __doc__ attribute:

def sum(a, b):
    '''Takes in two numbers, returns their sum'''
    return a+b

print(sum.__doc__)

Output

Takes in two numbers, returns their sum

Single-line docstrings in Python

Single-line docstrings are those that fit in one line.

The following are some standard guidelines for writing single-line docstrings:

  • Even though they are single-line, we still use triple quotes around these strings because they can be expanded easily later.
  • Closing quotation marks are on the same line as opening quotation marks.
  • There are no blank lines either before or after the docstring.
  • They must be concise and indicate what is in input and what is in output.

An example of single-line docstrings for a function:

def sum(a, b):
    '''Takes in two numbers, returns their sum'''
    return a+b

Multi-line Docstrings in Python

Multi-line docstrings consist of a summary line, just like a one-line docstring, followed by a blank line and a more detailed description.

The PEP 257 document provides standard conventions for writing multiline documents for various objects.

The most important and frequent are illustrated below.

1. Docstrings for Python Modules

Docstrings for Python Modules should list all available classes, functions, objects, and exceptions that are imported when the module is imported.

They should also have a one-line summary for each item.

For example, we want print the docstring of foo module:

import foo
print(foo.__doc__)

Output:

A test module for Tutorial Reference 

Classes:

    FooClass
    BarClass

Functions:

    do_something(object)
    do_something_else(object) -> string
    read_something(file) -> object
    load_something(string) -> object

Misc variables:

    __version__
    count_number
    available_formats

2. Docstrings for Python Functions

The docstring of a function or method must summarize its behavior and document its arguments and return values.

It should also list all exceptions that can be raised and other optional arguments.

For example:

def sum(a, b):
    '''
    Returns the sum of two decimal numbers.
            Parameters:
                    a (int): A decimal integer
                    b (int): Another decimal integer
            Returns:
                    a+b (int): sum of a and b
    '''
    return a+b


print(sum.__doc__)

3. Docstrings for Python Classes

The docstrings for classes should summarize their behavior and list public methods and instance variables.

Subclasses, constructors, and methods must each have their own docstrings.

For example, define a Person class:

class Person:
    """
    A class to represent a person.

    Attributes
        name : str
            first name of the person
        surname : str
            family name of the person
        age : int
            age of the person

    Methods
        info(additional=""):
            Prints the person's name and age.
    """

    def __init__(self, name, surname, age):
        """
        Constructs a person with name, surname and age
        Parameters:
            name : str
                first name of the person
            surname : str
                family name of the person
            age : int
                age of the person
        """

        self.name = name
        self.surname = surname
        self.age = age

    def info(self, additional=""):
        """
        Prints the name and age of the person.
        If the argument 'additional' is passed, then it is appended after the main info.

        Parameters:
            additional : str, optional
                More info to be displayed (default is None)
        Returns:
           None
        """
        print(f'My name is {self.name}{self.surname}. I am {self.age} years old.' + additional)

4. Docstrings for Python Scripts

The docstrings for Python script should document the script functions and command line syntax as a usable message.

It should serve as a quick reference to all functions and arguments.

5. Docstrings for Python Packages

The docstrings for a Python package is written in the package's __init__.py file.

  • It should contain all available modules and subpackages exported from the package.

For example, consider a package named greetings with a module hello_world. Your package structure looks like this:

greetings/
│
├── __init__.py
└── hello_world.py

In the __init__.py, you can write a simple docstring:

"""
greetings - A package for generating greetings.

Modules:
- hello_world: Prints a greeting message.
"""
from.hello_world import greet
Navigation