Close
Close

Python Docstrings


Generally, adding documentation is always a good practice while creating any project. In Python also, we can add documentation to functions, classes or class methods so that we get to know their functionality by reading the documentation. Such documentation in Python is called docstring

Defining a Docstring in Python


A docstring is created by adding a string enclosed within triple single quotes ''' ''' or triple double quotes """ """. These are written right after the definition of a function or class.

Python Single Line Docstring


These are the docstrings defined in a single line.

Let’s see an example of a single line docstring.

def cube(x):
    '''Returns the cube of the argument x.'''
    return x**3

print(cube(2))
Output
8

As you can see, by reading the docstring we can tell what the function does. Therefore, docstrings should be written such that we understand the overall functionality of the function by just reading it.

The same example is written using triple double quotes below.

def cube(x):
    """Returns the cube of the argument x."""
    return x**3

print(cube(2))
Output
8

We should implement the following practices while writing single line docstrings.

  • The opening and closing quotes should be on the same line.
  • The docstring should begin with a capital letter and end in a period (.).
  • No blank line should be left before and after the docstring.
  • One line docstring are more suitable for small and less complex functions.

Python Multiline Docstring


These are the docstrings which span into multiple lines.

Let’s see an example of a single line docstring.

def cube(x):
    """Returns the cube of the argument x.
	
    Argument: x must be a number
    Returns: cube of x
    """

    return x**3

print(cube(2))
Output
8

We should implement the following practices while writing single line docstrings.

  • The docstring should begin with a summary line followed by a blank line, followed by more details.
  • The summary line of the docstring can be on the same line as the opening triple quotes or on the next line.
  • The closing triple quotes should be on a new line after the docstring content ends.
  • Multiline docstrings are more suitable for classes or more complex functions.

Now that we have been introduced to docstrings, let’s see how to write multiline docstrings for functions and classes.

Python Docstrings for Functions


For small functions, it is advisable to write a single line docstring. For bigger and complex functions, multiline docstring should be written.

The following points should be kept in mind while writing multiline docstrings for functions or class methods.

  • The docstring should include a summary (preferably one liner summary) stating the objective of the function. The arguments and return values along with their data types should also be included in the docstring.
  • It should also list the exceptions which are raised
def divide(a, b):
    """Divides two numbers and returns the quotient.
    
    Args:
        a (int): An integer
        b (int): A non-zero integer
    	
    Raises:
        ValueError: b should not be 0
    	
    Returns:
        quotient (float): quotient of the division of a by b
    """
    
    if b == 0:
        raise ValueError()
    	
    quotient = a/b
    return quotient

print(divide(10, 2))
Output
5.0

You can see that we have included a short description of the functionality of the function in the start of the docstring. We have also included the information about the arguments, exception raised and the returned value.

Accessing Docstring of Functions


When we add a docstring to a function, it gets added as the __doc__ attribute of the function. Therefore, to access the docstring of a function, we need to access its __doc__ attribute.

def divide(a, b):
    """Divides two numbers and returns the quotient.
    
    Args:
        a (int): An integer
        b (int): A non-zero integer
    	
    Raises:
        ValueError: b should not be 0
    	
    Returns:
        quotient (float): quotient of the division of a by b
    """
    
    if b == 0:
        raise ValueError()
    	
    quotient = a/b
    return quotient

print(divide.__doc__)
Output

Divides two numbers and returns the quotient.

Args:

a (int): An integer

b (int): A non-zero integer

Raises:

ValueError: b should not be 0

Returns:

quotient (float): quotient of the division of a by b

We accessed the docstring of the divide function by writing divide.__doc__.

Python Docstrings for Classes


Let’s look at the points which should be considered while writing docstrings for classes.

  • The docstring should include a summary (preferably one liner summary) stating the behaviour of the class. It should also include all the attributes.
  • If the class inherits another class, then the details of its super class should be included. Also, if any method of the class is overriding a method of its super class, then the details of that method should be included.
  • The constructor and methods inside the class should have separate docstrings.
class Rectangle():
    """
    Rectangle class stores dimensions of rectangle.
    
    Attributes:
        length (float): Length of the rectangle
        breadth (float): Breadth of the rectangle
    """
    
    def __init__(self, l, b):
        """The constructor to initialize the object.
    	
        Args:
            l (float): Length of the rectangle
            b (float): Breadth of the rectangle
        """
        self.length = l
        self.breadth = b
	
    def getArea(self):
        "Returns the area of the Rectangle object."
        return self.length * self.breadth
	
rect = Rectangle(2,4)

print(rect.getArea())
Output
8

We added separate docstrings for the class, its constructor and method. In the docstring of the class, we included a summary of the class along with the details of the attributes.

Accessing Docstring of Classes, Constructors and Methods


Just like functions, if a docstring is added to a class, it gets added as its __doc__ attribute. 

Therefore, the docstring of the Rectangle class can be accessed as Rectangle.__doc__. The docstring of its constructor can be accessed as Rectangle.__init__.__doc__ and its method getArea as Rectangle.__getArea__.__doc__.

Let’s print all these docstrings in the last example.

class Rectangle():
    """
    Rectangle class stores dimensions of rectangle.
    
    Attributes:
        length (float): Length of the rectangle
        breadth (float): Breadth of the rectangle
    """

    def __init__(self, l, b):
        """The constructor to initialize the object.
    	
        Args:
            l (float): Length of the rectangle
            b (float): Breadth of the rectangle
        """
        self.length = l
        self.breadth = b
    	
    def getArea(self):
        "Returns the area of the Rectangle object."
        return self.length * self.breadth
		
rect = Rectangle(2,4)

print("**** Docstring of class Rectangle ****")
print(Rectangle.__doc__)

print("**** Docstring of the constructor class Rectangle ****")
print(Rectangle.__init__.__doc__)

print("**** Docstring of the getArea method of class Rectangle ****")
print(Rectangle.getArea.__doc__)
Output

**** Docstring of class Rectangle ****


Rectangle class stores dimensions of rectangle.

Attributes:

length (float): Length of the rectangle

breadth (float): Breadth of the rectangle

**** Docstring of the constructor class Rectangle ****

The constructor to initialize the object.

Args:

l (float): Length of the rectangle

b (float): Breadth of the rectangle

**** Docstring of the getArea method of class Rectangle ****

Returns the area of the Rectangle object.

For classes, we can also use the help() function to read docstrings. This function reads the docstrings of the class and its methods. For example, to read the docstrings of the class Rectangle and its methods, we need to write help(Rectangle).

Let’s print the docstrings in the previous example using help().

class Rectangle():
    """
    Rectangle class stores dimensions of rectangle.
    
    Attributes:
        length (float): Length of the rectangle
        breadth (float): Breadth of the rectangle
    """

    def __init__(self, l, b):
        """The constructor to initialize the object.
    	
        Args:
            l (float): Length of the rectangle
            b (float): Breadth of the rectangle
        """
        self.length = l
        self.breadth = b
	
    def getArea(self):
        "Returns the area of the Rectangle object."
        return self.length * self.breadth
	
rect = Rectangle(2,4)

help(Rectangle)
Output

Help on class Rectangle in module __main__:


class Rectangle(builtins.object)

 |  Rectangle(l, b)

 |  

 |  Rectangle class stores dimensions of rectangle.

 |  

 |  Attributes:

 |          length (float): Length of the rectangle

 |          breadth (float): Breadth of the rectangle

 |  

 |  Methods defined here:

 |  

 |  __init__(self, l, b)

 |      The constructor to initialize the object.

 |      

 |      Args:

 |              l (float): Length of the rectangle

 |              b (float): Breadth of the rectangle

 |  

 |  getArea(self)

 |      Returns the area of the Rectangle object.

 |  

 |  ----------------------------------------------------------------------

 |  Data descriptors defined here:

 |  

 |  __dict__

 |      dictionary for instance variables (if defined)

 |  

 |  __weakref__

 |      list of weak references to the object (if defined)

It is always good to have docstrings in your code so that understanding the functionality and properties of your functions and classes becomes easier whenever you or someone else goes through the code. So start including them in your programs.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Whether You Think You Can Or Think You Can’t, You’re Right.
- Henry Ford


Ask Yours
Post Yours
Doubt? Ask question