Python Class docstrings

In this tutorial we will discuss how to write docstrings for Classes in Python. In Python Classes, Docstrings are a means of explaining the purpose of the Class, the attributes of the Class, and sometimes also includes a list of methods belonging to the Class.

Docstrings can generally be written in any way, as long as they properly explain and document the accompanying code. There are however, several popular “Styles” or “Formats” of writing docstrings, which we will also discuss in this tutorial.


Docstrings in Python Classes

A Docstring for a Class is created by using a single multiline string, located on the first line after the name of the Class. This first line is automatically considered the docstring by Python. (We can use a regular string, but docstrings are quite large, and need to be split up across several lines)

Let’s create a simple class called “Calculator” and make a docstring for it. Here is the class without the docstring.

class Calculator:
    def __init__(self):
        self.prevSum = 0

    def add(num1, num2):
        return num1 + num2

To create a docstring for this Class, we need to include two main things. An short description about the class, and a list of attributes and their datatypes.

class Calculator:
    """Contains various functions to perform common 
    mathematical operations between two numbers
    
    prevSum : Integer
        Stores the value of the previous operation"""

    def __init__(self):
        self.prevSum = 0

    def add(num1, num2):
        return num1 + num2

This is a clear and concise docstring that explains what the Class is about, and what variables it has (and their types).


Method Docstrings in Python

So far we have only documented the Class itself, and the attributes belonging to it. We also need to document the methods however. This is usually done on a method-by-method basis, and not within the Docstring for the Class.

In other words, instead of including the method documentation inside the Docstring for the Class, we create separate docstrings for each method. Just like Classes, this is done by creating a multi-line string on the first line of each method.

class Calculator:
    """Contains various functions to perform common 
    mathematical operations between two numbers
    
    prevSum : Integer
        Stores the value of the previous operation"""

    def __init__(self):
        """Initializes class attributes"""
        self.prevSum = 0

    def add(num1, num2):
        """Takes two integers and prints out the sum"""
        return num1 + num2

Our documentation for our Class is now fully complete! Everything has been labelled appropriately and described.


Google Docstrings

As mentioned earlier, there are various popular styles that are widely used amongst Python programmers, one of which was introduced by Google. It is popular because it is an easy format to use, and is very easily readable.

So let’s convert our current docstring into a Google styled docstring.

class Calculator:
    """Contains various functions to perform common 
    mathematical operations between two numbers
    
    Attributes:
        prevSum (int): Stores value of previous operation"""

    def __init__(self):
        """Initializes class attributes
        
        Args:
            No arguments
        """

        self.prevSum = 0

    def add(num1, num2):
        """Calculate sum of two numbers
        
        Args:
            num1 (int): First Value
            num2 (int): Second Value
            
        Returns:
            Sum of num1 and num2"""

        return num1 + num2

Our code is much more verbose now, but much more descriptive and easy to follow.

If you are interested in learning more about the Google Docstrings format, as well as other popular docstring styles, follow the link!


Printing out Docstrings

Now let’s print out the docstring for our Class using the help() function. Every function, class and module has a built-in __doc__ attribute. By invoking this method we can have the docstring returned which we can then print out.

If you print out the Class docstring, using the __doc__ attribute, only the Class docstring will be returned. This is shown in the example below.

print(Calculator.__doc__)
Contains various functions to perform common 
    mathematical operations between two numbers

    Attributes:
        prevSum (int): Stores value of previous operation

However, if we use the help() function, it will print the docstrings for the Class methods as well.

help(Calculator)
class Calculator(builtins.object)
 |  Contains various functions to perform common
 |  mathematical operations between two numbers
 |
 |  Attributes:
 |      prevSum (int): Stores value of previous operation
 |
 |  Methods defined here:
 |
 |  __init__(self)
 |      Initializes class attributes
 |
 |      Args:
 |          No arguments
 |
 |  add(num1, num2)
 |      Calculate sum of two numbers
 |
 |      Args:
 |          num1 (int): First Value
 |          num2 (int): Second Value
 |
 |      Returns:
 |          Sum of num1 and num2
 |
 |  ----------------------------------------------------------------------

It’s also a lot neater and nicely formatted so use this function whenever you can.


This marks the end of the Python Class docstrings Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments