Python Docstrings

In this tutorial post, we will learn about docstring in Python. Docstring, also known as Python Documentation String is used to associate documentation with Python modules, functions(methods), and classes.

Docstring is nothing else than a simple multiline string that specifies what a function, class or module does. If you have ever opened the file of any module you must have seen the docstring written in it. Any function we import from any module also has docstring.

Also read: How to call a user-defined function in Python 3?

Docstring in Python

For declaring docstring in our functions or classes we use triple-double quotes(“””   “””). The documentation of functions is enclosed inside these quotes.

Let’s see the example:

def fun(a,b):
    """Function for calculating mean """
    mean=(a+b)/2
    return mean

Inside the function, the string Function for calculating mean enclosed inside the triple-double quotes is docstring. Inside the quotes, we can write the information or documentation of the functions.

The syntax for fetching docstring from code:

functionName.__doc__
if __name__ == '__main__':

    #fetching docstring
    print(fun.__doc__)
    print(fun(80,30))

Combining whole code:

def fun(a,b):
    """Function for calculating mean """
    mean=(a+b)/2
    return mean

if __name__ == '__main__':
    print(fun.__doc__)
    print(fun(80,30))

Output:

Function for calculating mean 
55.0

If we are working on a complex or big project it is good practice to write documentation for the functions used in the program using docstring in Python like what parameters function takes, what it returns and many more important things.

I hope you have understood the docstring in Python. If you have any queries related to this post please comment below.

Also read: Python string rjust() and ljust() methods

Leave a Reply

Your email address will not be published. Required fields are marked *