Docstring in Python | Rules, Example

The documentation string in Python language is known as docstring. It provides the easiest and powerful feature for documenting your code in Python.

In other words, a docstring in Python allows us to add quick information to various classes, modules, methods, and functions.

We usually write them at the start of the definition of class, function, module, and method.

That is, docstring should be the first statement inside the definition of class, function, module, and method.

Inside the docstring, always write what a class or function does and not how it functions.

The Python official language recommends using triple double quotation marks (” ” “) or triple single quotation marks (‘ ‘ ‘) to write docstrings. Look at the following example code below.

# Function with a Docstring.
def get_prime_number():
    """Getting the list of prime numbers between 1 to 20."""

Basic Standard Rules to write Docstring in Python


Python’s official language recommends a specific way to write docstring. There are the following standard rules to write docstring in Python.

1. We must write docstring in the first line of the definition of Python class, module, function, and method.

2. The Python’s official language recommends using ”’triple single quotes”’ or “””triple double quotes””” for writing docstring. You can also use “double quotes”.

3. The documentation string should begin with a capital letter and end with a period (.).

4. The first line should be a brief description of the function, class, or module.

5. If you are writing multiple lines in the documentation string, then the second line should be blank and start writing with the third line. This format will give you a good visualization to read the documentation string.

Purpose of Writing Docstring in Python


In Python, both documentation string and multi-line comments in triple quotation marks are strings. A sting is an executable object.

If we do not assign to it in a variable, then the garbage collector collects it after the code has been executed. Therefore, it is used for multi-line comments and ignored by the Python interpreter.

But when we write a multi-line string (docstring) just immediately after the definition of class, function, module, or method, then the Python interpreter does not ignore it.

This is the difference between multi-line comments and docstring. The major advantage of using docstring in a program is that it is available for use at runtime.

We can access docstring of any function using the below syntax:

object.__doc__

In the above syntax, it is prefixed with double underscores (_ _) and suffix with double underscores (_ _).


Let’s take an example program in which we will access a multiline docstring of a function. Look at the program code below.

# Function with a Docstring.
def getSum(x, y):
    """This is a docstring

       This method takes two argument values and returns the summation of it."""
    print("Sum = ", (x + y))
getSum(20, 40) # Calling function.
print(getSum.__doc__) # Calling __doc__ method to print docstring.
Output:
      Sum =  60
      This is a docstring

       This method takes two argument values and returns the summation of it.

Note:

We do not need to follow indentation while writing multiple lines of documentation string. Let’s take an example of it.

# Function with a Docstring.
def getSum(x, y):
    """This is a docstring
This method takes two argument values and returns the summation of it."""
    print("Sum = ", (x + y))
getSum(20, 40)
print(getSum.__doc__)
Output:
      Sum =  60
      This is a docstring
      This method takes two argument values and returns the summation of it.

Function Docstring Example


We can write function docstring after the definition function or on the top of a function. This is the powerful use of docstring in Python. Function docstring mostly focuses on the on the explaining the operation of function. Let’s take an example of it.

# Function with a Docstring.
def getSquare(num):
    '''This method takes a number num and returns the square of its value.'''
    return num * num
print(getSquare.__doc__) # Accessing docstring.
sq_value = getSquare(20) # Calling function.
print(sq_value)
Output:
      This method takes a number num and returns the square of its value.
      400

Class Docstring Example


Python language recommends the following structure while using docstring for documenting a class.

  • First line blank
  • A summary: usually a single line.
  • Second line blank
  •  Any further description regarding the docstring.

Let’s take an example in which we will write docstring for a class. Look at the example code below.

class Rectangle:
    """
    This is a class for calculating the area of a rectangle.

        Parameters:
        l (int) : The length of rectangle.
        b (int) : The breadth of rectangle.
    """
print(Rectangle.__doc__)
Output:
      This is a class for calculating the area of a rectangle.

        Parameters:
        l (int) : The length of rectangle.
        b (int) : The breadth of rectangle.

Difference between Docstring and Comment in Python


There are the following difference between docstring and comment in Python. They are as:

1. Docstring explains about the entire function or method whereas, comment only explains about a specific line of code.

2. We can read docstring of any function or class using syntax: functionName.__doc__ or className.__doc__. Whereas there is no predefined method in Python to read the comment of any block of code.

3. We can also read docstring using the syntax help(<object>). For example:

def get_square(x):
    "This is a method for calculating the square of a number."
    return x * x # It will calculate the square of a number and return the output.
help(get_square)
Output:
      Help on function get_square in module __main__:

get_square(x)
    This is a method for calculating the square of a number.

In this example, we have used a predefined function help() that helps the programmer know the documentation about class, function, module, and method.


In this tutorial, we have elaborated about docstring in Python with various examples. Hope that you will have understood the basic points of docstring and how to make it really easy to document your code.
Thanks for reading!!!
Next ⇒ Python vs C⇐ Prev Next ⇒