What is Docstring and how to write docsrting in python

Published by admin on

Python how to write docstring

Docstring in python :

A docstring is a string that is used for documentation of a module,function,class or method in python. This string comes as the first statement after the name of the function , module etc . The value of a docstring can be printed out by using _doc_ attribute of the object. So, if you want to know what a system module does, just print out its docstring. e.g. to know about ‘int’, use the following :

print (int.__doc__)

How to write docstring for your own custom function ?

We can write single line or multiline ‘docstring’ for any custom methods , class, function or module. Triple quotes are used as opening and closing quotes for the docstring. Let me show you with a simple example :

def my_func(x,y):
    """Find the multiplication of x,y and return the result"""
    return x*y

print (my_func.__doc__)

It will print :

Find the multiplication of x,y and return the result

Multiple line docstring is same as above. Triple quote is used for multiline docstring. If you want to write more detail in documentation, you can write in multilines. Example :

def my_area(h,w):
    """Find the area

    h -- height
    w -- width
    return x*y

print (my_area.__doc__)

It will print :

Find the area

    h -- height
    w -- width

We should always try to comment on code wherever possible. Most of the time we forget what we wrote months ago : commenting will help on that. Also , it will be a lot more easier for any other programmer to maintain the code in future. Don’t you think ?

Similar tutorials :

Categories: python


Leave a Reply

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