Docstrings in Python

Python docstrings are the string literals that appear right after the definition of a function, method, class, or module.

Example:

Python

def square(n):
    '''Takes in a number n, returns the square of n'''
    print(n**2)
square(5) 

Output: 25

Here,
'''Takes in a number n, returns the square of n''' is a docstring which will not appear in output.

Python doc attribute Whenever string literals are present just after the definition of a function, module, class or method, they are associated with the object as their doc attribute. We can later use this attribute to retrieve this docstring.

Python

def square(n):
    '''Takes in a number n, returns the square of n'''
    return n**2

print(square.__doc__)
# Output: Takes in a number n, returns the square of n