Comments are used to explain the code and make it more readable. They are ignored by the Python interpreter there are two types of comments.
Single-line comments start with a #
.
# This is a single-line comment
x = 5 # This is an inline comment
Multi-line comments can be written using triple quotes ('''
or """
). These are also known as docstrings when used to document functions, classes, and modules.
"""
This is a multi-line comment.
It can span multiple lines.
"""
Proper documentation helps in understanding the purpose and usage of different parts of your code. Python provides several ways to document your code effectively.
Docstrings are used to document modules, classes, methods, and functions. They are written inside triple quotes and placed right after the definition.
Module Docstring
"""
This module provides an example of using docstrings to document code.
It includes examples of functions and classes.
"""
def add(a, b):
"""
Adds two numbers.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
return a + b
Function Docstring
def multiply(a, b):
"""
Multiplies two numbers.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The product of the two numbers.
"""
return a * b
Class and Method Docstring
class Calculator:
"""
A simple calculator class.
"""
def __init__(self, value=0):
"""
Initializes the calculator with a starting value.
Parameters:
value (int, optional): The starting value. Defaults to 0.
"""
self.value = value
def add(self, amount):
"""
Adds a number to the current value.
Parameters:
amount (int): The number to add.
"""
self.value += amount
def get_value(self):
"""
Returns the current value.
Returns:
int: The current value.
"""
return self.value
The help()
function in Python can be used to display the docstring of modules, functions, classes, and methods.
print(help(add))
print(help(Calculator))
You can use external tools to generate documentation from your code's docstrings. Some popular tools include:
Example of using pydoc
:
$ pydoc -w your_module