Skip to content

Python3 Comments

In Python, comments do not affect the execution of a program but make the code easier to read and understand.

Python has single-line comments and multi-line comments.


In Python, single-line comments start with #. All text after the # symbol is treated as a comment and will not be executed by the interpreter.

# This is a comment
print("Hello, World!")
# This is also a comment

In Python, multi-line strings (text blocks surrounded by three single quotes ''' or three double quotes """) can be used as multi-line comments.

#!/usr/bin/python3

'''
This is a multi-line comment, using three single quotes
This is a multi-line comment, using three single quotes
This is a multi-line comment, using three single quotes
'''
print("Hello, World!")
#!/usr/bin/python3

"""
This is a multi-line comment, using three double quotes
This is a multi-line comment, using three double quotes
This is a multi-line comment, using three double quotes
"""
print("Hello, World!")

Note: Although multi-line strings are used here as multi-line comments, they are actually strings. As long as we don’t use them, they won’t affect the program’s execution.

These strings can be placed in certain positions in the code without causing actual execution, thus achieving the effect of comments.

In Python, multi-line comments are defined by three single quotes ''' or three double quotes """. This commenting method cannot be nested.

When you start a multi-line comment block, Python will treat all subsequent lines as comments until it encounters another set of three single quotes or three double quotes.

Nesting multi-line comments will cause a syntax error:

'''
This is an outer multi-line comment
It can contain some descriptive content

    '''
    This is an attempt to nest a multi-line comment
    It will cause a syntax error
    '''
'''

In this example, the inner three single quotes are not correctly recognized as the end of the multi-line comment but are interpreted as a regular string, which will cause the code structure to be incorrect.

Correct approach: Use single-line comments for nesting

'''
This is an outer multi-line comment
It can contain some descriptive content

# This is an inner single-line comment
# It can be nested inside a multi-line comment
'''

Python’s Docstring is a special type of comment used to add documentation to functions, classes, modules, etc. It is similar to Java’s Javadoc but more powerful and flexible.

Unlike regular comments, Docstrings can be accessed directly through the __doc__ attribute and can also be viewed using the help() function.

Docstrings are enclosed in three double quotes """ or three single quotes ''' and placed at the beginning of functions, classes, or modules.

def add(a, b):
    """Returns the sum of two numbers"""
    return a + b

# Access via the __doc__ attribute
print(add.__doc__)  # Output: Returns the sum of two numbers
def add(a, b):
    """Returns the sum of two numbers"""
    return a + b

# Use the help() function
help(add)

Expected output:

Help on function add in module __main__:

add(a, b)
    Returns the sum of two numbers

Extracting Documentation with the inspect Module

Section titled “Extracting Documentation with the inspect Module”

Python’s standard library provides the inspect module, which can directly extract documentation content:

import inspect

def add(a, b):
    """Returns the sum of two numbers"""
    return a + b

# Use inspect.getdoc() to get the documentation
print(inspect.getdoc(add))  # Output: Returns the sum of two numbers

Expected output:

Returns the sum of two numbers

For complex functions, you can use multi-line Docstrings:

def calculate(a, b, operation="add"):
    """
    Performs a mathematical operation

    Parameters:
        a: first number
        b: second number
        operation: operation type, options are "add", "subtract", "multiply"

    Returns:
        the calculation result
    """
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    else:
        raise ValueError("Unsupported operation")

# View the full documentation
help(calculate)

Expected output:

Help on function calculate in module __main__:

calculate(a, b, operation='add')
    Performs a mathematical operation

    Parameters:
        a: first number
        b: second number
        operation: operation type, options are "add", "subtract", "multiply"

    Returns:
        the calculation result

Docstrings can also be used for classes:

class Person:
    """Person class, used to represent basic information about a person"""

    def __init__(self, name, age):
        """
        Initializes a person object

        Parameters:
            name: name
            age: age
        """
        self.name = name
        self.age = age

    def introduce(self):
        """Introduces this person"""
        return f"My name is {self.name}, I am {self.age} years old"

# Access class documentation
print(Person.__doc__)

# Access method documentation
print(Person.introduce.__doc__)

Expected output:

Person class, used to represent basic information about a person
Introduces this person

There are several Docstring styles in Python, the most commonly used being:

  • Google style: Uses space indentation with clear labels for parameters and return values.
  • Sphinx/reST style: Uses a colon prefix, e.g., :param name:.
  • NumPy style: Similar to Google style but with slightly different formatting.

It is recommended to choose one style and remain consistent within a project.