Docstrings are used in Python to provide documentation for modules, classes, functions, and methods. They are enclosed in triple quotes ('''
or """
) and placed as the first statement within these entities. Docstrings help in generating automatic documentation and can be accessed using various tools and libraries.
def add(a, b):
"""
This function takes two arguments and returns their sum.
Parameters:
a (int): The first number to be added.
b (int): The second number to be added.
Returns:
int: The sum of the two numbers.
"""
return a + b
class Calculator:
"""
This class represents a simple calculator.
Methods:
add(a, b): Returns the sum of two numbers.
subtract(a, b): Returns the difference of two numbers.
"""
def add(self, a, b):
"""Return the sum of two numbers."""
return a + b
def subtract(self, a, b):
"""Return the difference of two numbers."""
return a - b
You can access docstrings using the __doc__
attribute of the function, class, or module.
print(add.__doc__)
calc = Calculator()
print(calc.add.__doc__)
print(calc.subtract.__doc__)
Docstrings can be used to generate documentation automatically using tools like pydoc
and sphinx
. The generated documentation can be in various formats, such as HTML, PDF, or plain text.
By including docstrings in your code, you improve code readability and provide essential documentation to fellow developers who might use or maintain your code.