We can provide documentation to Modules, functions , class and methods by using docstrings.
Docstrings for documentation about functions, methods , class and modules in Python using formats
Documentation of functions
We can include details about the function for user understanding by writing some text about the function. This we can do by using three single quotes or by using three double quotes. It should be just after the function declaration.
def my_add(x,y):
'''Takes two inputs and returns the sum'''
return x+y
print(my_add(5,7)) #12
print(my_add.__doc__)
By using __doc__ we are getting the output for second print command.
Takes two inputs and returns the sum
We should include about the functions, arguments, return value, error if any and additional notes in our Docstrings. Here is one sample.
def my_add(x,y):
""" Adds to inputs
Args:
x (int) : first integer to be addded
y (int) : second integer to be added
Raises:
TypeError: can only concatenate str (not "int") to str
Returns:
Sum of two inputs.
Notes:
Visit www.plus2net.com for more info
"""
return x+y
print(my_add.__doc__)
class my_tutorial():
'''This is about the tutorial to learn the language.'''
my_subject='Python' # class attributes
#instance attributes
def __init__(self,name,mark):
self.name= name
self.mark= mark
def discount(self):
'''This is about the discount offers.'''
if(self.mark > 50):
return "Discount is avilable"
else:
return "No Discount"
Alex=my_tutorial('Alex',40) # object is defined
print(Alex.discount()) # No Discount # Discount method is used
print(Alex.my_subject) # Python # Class attribute is used
print(my_tutorial.__doc__)
print(my_tutorial.discount.__doc__)
#using the object
print(Alex.__doc__)
print(Alex.discount.__doc__)
Output is here
No Discount
Python
This is about the tutorial to learn the language.
This is about the discount offers.
This is about the tutorial to learn the language.
This is about the discount offers.
Documentation of modules
We will create one module like this and give the name my_module.py
'''This is module level docstrings'''
class my_tutorial():
'''This is about the tutorial to learn the language.'''
my_subject='Python' # class attributes
#instance attributes
def __init__(self,name,mark):
self.name= name
self.mark= mark
def discount(self):
'''This is about the discount offers.'''
if(self.mark > 50):
return "Discount is avilable"
else:
return "No Discount"
This module my_module.py we will import and print the docstrings of module, class and object. Our file docstrings_model.py is here