PYTHON

Comments and documentation


Comments and Documentation in Python

 

Comments

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.

1. Single-line Comments

Single-line comments start with a #.

# This is a single-line comment
x = 5  # This is an inline comment

 

2. Multi-line Comments

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.
"""

Documentation

Proper documentation helps in understanding the purpose and usage of different parts of your code. Python provides several ways to document your code effectively.

1. Docstrings

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

 

Ueses

The help() function in Python can be used to display the docstring of modules, functions, classes, and methods.

print(help(add))
print(help(Calculator))

 

External Documentation Tools

You can use external tools to generate documentation from your code's docstrings. Some popular tools include:

  • Sphinx: Generates HTML documentation from docstrings.
  • pydoc: Generates text documentation from docstrings and can be used to start a local web server to view documentation.

Example of using pydoc:

$ pydoc -w your_module

 


PYTHON