Add Docstring to a Python Function

Docstring provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It’s specified in source code that is used, like a comment, to document a specific segment of code. It also describe what the function does,not how.

Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.

Rules for writing a docstrings:

  • There's no blank line either before or after the docstring.
  • If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
  • The doc string line should begin with a capital letter and end with a period.
  • Even though If there are single-lined, we still use the triple quotes around these docstrings as they can be expanded easily later.

Using triple double quotes

def add(a, b):
    """Takes in two numbers, returns their sum."""
    return a+b

print("Using __doc__:")
print(add.__doc__)
  
print("Using help:")
help(add)

Output:

Using __doc__:
Takes in two numbers, returns their sum.
Using help:
Help on function add in module __main__:

add(a, b)
    Takes in two numbers, returns their sum.

Using triple single quotes

def product(a, b):
    '''Takes in two numbers, returns their product.'''
    return a*b

print("Using __doc__:")
print(product.__doc__)
  
print("Using help:")
help(product)

Output:

Using __doc__:
Takes in two numbers, returns their product.
Using help:
Help on function product in module __main__:

product(a, b)
    Takes in two numbers, returns their product.

One-line Docstring

It fits in one line. The closing quotes are on the same line as the opening quotes.

def power(a, b):
    """Returns a raised to power b."""
    return a**b
  
print(power.__doc__)

Output:

Returns a raised to power b.

Multi-line Docstring

It is consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. 

def add(a, b):
    '''
        Returns the sum of two  numbers.

            Parameters:
                a (int): A integer
                b (int): Another integer

            Returns:
                sum (int):The sum of a and b
    '''
    sum=a+b
    return sum

print(add.__doc__)

Output:

   Returns the sum of two  numbers.

            Parameters:
                    a (int): A integer
                    b (int): Another integer

            Returns:
                    sum (int):The sum of a and b
Tags