Python Docstrings : How to document your Python code ?

python-docstrings

In this article we will see how to generate docstring for your python code. Documentation is a very important step in the development of a program. It allows you to comment your code and know what each part of your code does. If the code is shared, other contributors can also know what you have developed as a function thanks to this documentation. We will see in the following how to declare its docstring and the different formats to do so.

Python Docstrings

What is a Docstring?

The term docstring comes from the abbreviation documentation string, it is intended to describe all your code by setting up a definition for functions, classes and modules. It is located at the beginning of each header of a function, class or module. In theory, all functions should have a docstring, this allows your python program to inspect this docstring at runtime. This allows the programmer to have an interactive area system.

The docstrings are accessible by __doc__ attribute of the objects.

Docstring Example

Let’s start with some simple examples to create a docstring :

def squared(x):
    '''Return the number in parameter raised squared.'''
    return x*x

print(squared.__doc__)
Output:
Return the number in parameter raised squared.

In this example we have defined a squared function that returns the number as a squared parameter. We have declared a docstring that explains what the function does. To get the docstring of a function, we need to display the doc attribute (print(squared.__doc__))

In this other example, we will create a new module and see how to declare a docstring for a module, a class and a method. Let’s start by creating the pokemon module that contains the following class:

"""
Creation of the pokemon module.
It allows you to create new pokemon and to modify the name of the pokemon you want.
"""

class Pokemon(object):
    '''Initilization of the pokemon class.'''
    def __init__(self,number,name,type):
        self.number = number
        self.name = name
        self.type = type

    def getName(self):
        '''Getting the name of the pokemon.'''
        return self.name

We created this module in a python file called pokemon.py. Now we will define another file that will import this newly created module. To find out what this module contains and the different classes/functions it contains, we can use the help() function:

import pokemon
help(pokemon)

This is what the help() function gives us:

python-docstring-example

We can also use the help() function to display the docstring of the pokemon class and the getName() method :

import pokemon
help(pokemon.Pokemon)
help(pokemon.Pokemon.getName)
python-docstring-example2

Single-Line Docstrings

You can do a docstring on a single line if you want, it will be easier to read your code. By convention, a docstring always starts with a capital letter and ends with a period. It is best not to insert spaces at the beginning and end of the docstring. You can use single quotes or double quotes (as long as the beginning and end quotes are the same).

Here is an example of a Single-Line Docstrings :

pokemon.py

def getName(self):
    '''Returns the name of the pokemon.'''

    return self.name

def getType(self):
    """Returns the type of the pokemon."""

    return self.type

game.py

import pokemon
help(pokemon.Pokemon.getType)
help(pokemon.Pokemon.getName)
Output:
Help on function getType in module pokemon:
getType(self)
Returns the type of the pokemon.
Help on function getName in module pokemon:
getName(self)
Returns the name of the pokemon.

Multi-Line Docstrings

A docstring can also be written on several lines if necessary (if the description is long it is better to use this method). The docstring should always be enclosed in single or double quotes. Its first line is interpreted as a summary, so it is recommended to write it the same way as a simple-line docstring.

Here is an example by adding a function in our pokemon class :

def describePokemon(self):
    """Returns the full description of the pokemon.

       This function returns a string that contains the number,
       name and type of the pokemon.
    """

    return "pokemon number"+self.number+"is "+self.name+" , it's a "+self.type+" type pokemon."
import pokemon
#help(pokemon.Pokemon.getType)
#help(pokemon.Pokemon.getName)
help(pokemon.Pokemon.describePokemon)
Output:
Help on function describePokemon in module pokemon:
describePokemon(self)
Returns the full description of the pokemon.
This function returns a string that contains the number, name and type of the pokemon.

Docstring Formats

There are several docstring formats (Unfortunately for us ! 🙂 ). Here is a list of the different existing formats:

  • reStructured text (reST) / Sphinx
  • Google Docstrings
  • NumPy/SciPy Docstrings

reStructured text (reST)/Sphinx : The first format is the official Python standard. It is based on the syntax of the lightweight markup language reStructured text (reST) which is similar to the use of Markdown. It provides us with several keywords that we need to add in our docstring to comply with the standard, for example:

  • param and type: Parameter and its variable type
  • return and rtype: Specify both the return value and type of the function or method

I let you consult the documentation on the format to have all the keywords that can be used.

Here is an example of the reStructured text (reST)/Sphinx format:

    def setType(self,type):
        """Change the pokemon type.

            The parameter value is stored in the type
            variable of the pokemon class.

            :param type: type pokemon
            :type type: string
            :return: no value
            :rtype: none
            """

        self.type = type
        return

        return self.type

import pokemon
#help(pokemon.Pokemon.getType)
#help(pokemon.Pokemon.getName)
#help(pokemon.Pokemon.describePokemon)
help(pokemon.Pokemon.setType)
Output:
Help on function setType in module pokemon:
setType(self, type)
Change the pokemon type.
The parameter value is stored in the type variable of the pokemon class. 
:param type: type pokemon 
:type type: string
:return: no value
:rtype: none

Google Docstrings : This format is less dense than the previous one. It remains easy to understand. Here is an example using the same function as before:

    def setType(self,type):
        """Change the pokemon type.

            The parameter value is stored in the type
            variable of the pokemon class.

            Args:
                type (float): pokemon type

            Returns:
                no value
            """


        self.type = type
        return
import pokemon
help(pokemon.Pokemon.setType)
Output:
Help on function setType in module pokemon:
setType(self, type)
Change the pokemon type.
The parameter value is stored in the type variable of the pokemon class. 
Args: 
    type (float): pokemon type
Returns: 
    no value

NumPy/SciPy Docstrings : Here is an example of the previous function using this format :

    def setType(self,type):
        """Change the pokemon type.

            The parameter value is stored in the type
            variable of the pokemon class.

            Parameters
            ----------
            type : string
                type pokemon
                
            Returns
            -------
            no value
            """

        self.type = type
        return
import pokemon
help(pokemon.Pokemon.setType)
Output:
Help on function setType in module pokemon:
setType(self, type)
Change the pokemon type.
The parameter value is stored in the type variable of the pokemon class. 
Parameters 
---------- 
type : string 
    type pokemon
Returns
------- 
no value

Conclusion

It is important to respect the formats of a docstring so that it is understandable to everyone. This allows us to better understand the source code, but also to generate manuals for the applications we develop in python.

I hope that this tutorial has helped you in the creation of a docstring, don’t hesitate to send me a comment! 🙂

Back to the Python section

Published
Categorized as Python

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Leave a comment

Your email address will not be published.