When implementing a function, a class or a module, it is important to include a documentation so that it will be easier to understand and maintain in future. Most people tend to overlook this part as they may regard it as trivial or time-consuming.  While this may seem okay for simple programs, it can easily become a readability barrier if the program becomes more complex and involves more than just a single developer. You should write programs with your future self in mind, you do not want to write a class and returning six months later, you can't easily remember how it works or what purpose it is intended to accomplish.

Documenting functions and other objects offers the following advantages:

  • Boosts code readability making it easier to understand its usage and purpose.
  • Makes it easy to maintain the code.
  • Makes it easy for IDEs and editors to assist in debugging.

Python offers a very convenient way for writing documentations through the use of docstrings

What are docstrings?

A docstring is simply a string written using the triple quotes format, that appears as the first statement in a function, a method, a class or a module. It should, at least, give a quick summary of the object's usage and purpose.

Consider the following example.

ExampleEdit & Run

docstring in functions

def add(a, b):
    '''calculates the sum of two numbers, a and b'''
    return f'{a} + {b} = {a + b}'

print(add.__doc__)
Output:
calculates the sum of two numbers, a and b[Finished in 0.010323900962248445s]

As shown in the above example,  Python automatically assigns our docstring to the __doc__ attribute. We can use this attribute to conveniently retrieve the docstring of an object. In the following examples we retrieve the docstrings of some builtin functions.

ExampleEdit & Run
print(sum.__doc__)
Output:
Return the sum of a 'start' value (default: 0) plus an iterable of numbersWhen the iterable is empty, return the start value.This function is intended specifically for use with numeric values and mayreject non-numeric types.[Finished in 0.010012791957706213s]
ExampleEdit & Run
print(range.__doc__)
Output:
range(stop) -> range objectrange(start, stop[, step]) -> range objectReturn an object that produces a sequence of integers from start (inclusive)to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.These are exactly the valid indices for a list of 4 elements.When step is given, it specifies the increment (or decrement).[Finished in 0.009687755024060607s]

access the docstring with the help() Function

The docstring is also included in the help message when we call the help() function. However, the help() function includes other details about the target object  that may have nothing to do with the docstrings.

ExampleEdit & Run
def add(a, b):
    '''calculates the sum of two numbers, a and b'''
    return f'{a} + {b} = {a + b}'

help(add)
Output:
Help on function add in module __main__:add(a, b)    calculates the sum of two numbers, a and b[Finished in 0.03755477489903569s]

Docstring in classes

With classes, the documentation text should summarize the behavior of the class, list the public methods and attributes and also  include any other text that may help someone understand the class better.  Each of the public methods should also contain their own docstrings.

ExampleEdit & Run
class Dog:
    '''A class to represent a dog.
    ...

    attributes
    ----------
    name: str 
        name of the dog
    owner: str
        name of the dog owner.
    age: int
        age of the dog.
    
    methods
    --------
    get_info() -> str:
        Print information about the dog i.e name, age, and owner'''
    
    def __init__(self, name, age, owner):
        self.name = name
        self.age = age
        self.owner = owner

    def get_info(self, mini = False):
         '''Print name, age and the owner of the dog.

           If 'mini' is True, print just name and age.
           
           returns
           .......
               None'''
         if mini:
              print(self.name, self.age )
         else:
              print('dog: ', self.name)
              print('age: ', self.age)
              print('owner: ', self.owner)


d1 = Dog('Rocky', 2, 'John')

print(d1.__doc__)
Output:

A class to represent a dog.

...

attributes
----------
    name: str
        name of the dog
    owner: str
        name of the dog owner.
    age: int
        age of the dog.

methods
------------
    get_info() -> str:
        Print information about the dog i.e name, age, and owner

Docstring in modules and packages

For modules/scripts, the docstring appears as the first statement at the top of the file. It should offer general information about the functions and classes defined there. The following example demonstrates this with a module defined in the standard library.

ExampleEdit & Run
import string

print(string.__doc__)
Output:
A collection of string constants.Public module variables:whitespace -- a string containing all ASCII whitespaceascii_lowercase -- a string containing all ASCII lowercase lettersascii_uppercase -- a string containing all ASCII uppercase lettersascii_letters -- a string containing all ASCII lettersdigits -- a string containing all ASCII decimal digitshexdigits -- a string containing all ASCII hexadecimal digitsoctdigits -- a string containing all ASCII octal digitspunctuation -- a string containing all ASCII punctuation charactersprintable -- a string containing all ASCII characters considered printable[Finished in 0.01624925504438579s]

With packages, the docstring is written at the top of the __init__.py file.