Comment code in Python

In this post, we will explore the importance of commenting code in Python, the different types of comments, and best practices to effectively utilize comments in your Python projects.

Comment code in Python
Photo by Guilherme Lahmann / Unsplash

How to use comments properly in Python code

Comments are an essential aspect of any programming language, including Python. They provide a means to add human-readable explanations and annotations within your code, making it more comprehensible and maintainable. In this post, we will explore the importance of commenting code in Python, the different types of comments, and best practices to effectively utilize comments in your Python projects.

The Significance of Code Comments

Python code comments offer several benefits that greatly enhance the development process and collaboration among team members. Let's take a closer look at why commenting code is crucial:

Improved Readability and Comprehension

Comments provide additional context and explanations for your code, making it easier for both yourself and others to understand the purpose and functionality of different sections. Well-commented code is more readable and reduces the time required to decipher its intricacies.

Documentation and Code Maintenance

Comments serve as documentation that helps future developers maintain and modify your codebase. When revisiting your own code or sharing it with a team, comments act as valuable reference points, making it easier to identify and comprehend the logic behind specific code blocks.

Communication and Collaboration

Code comments facilitate effective communication among team members working on the same project. They allow you to convey your thoughts, ideas, and intentions, enabling seamless collaboration and reducing misunderstandings.

Types of Code Comments in Python

Python offers two primary types of code comments: single-line comments and multi-line comments.

Single-Line Comments

Single-line comments are used to provide short explanations or annotations for a specific line of code. They are denoted by the hash symbol (#) and extend from the hash symbol to the end of the line. Here's an example:

# This is a single-line comment

Multi-Line Comments

Multi-line comments, also known as block comments, are used to provide detailed explanations or document larger sections of code. In Python, there is no specific syntax for multi-line comments. However, you can enclose multiple lines of text within triple quotes (either single or double). Here's an example:

This is a multi-line comment.
It can span across multiple lines.
Use it for longer explanations or documentation.

Multi-Line Comments Within a Function a.k.a. Docstrings

In Python, you can use triple quotes (""") to create multi-line comments within a function. These comments are enclosed between triple quotes and can span multiple lines. They are often referred to as docstrings, as they are commonly used to document functions and provide detailed explanations of their purpose, parameters, and return values.

Let's consider an example of a function that calculates the area of a rectangle and uses a multi-line comment to document its functionality:

def calculate_rectangle_area(length, width):
    Calculates the area of a rectangle.

    length (float or int): The length of the rectangle.
    width (float or int): The width of the rectangle.

    float or int: The area of the rectangle.
    area = length * width
    return area

In the above code snippet, the calculate_rectangle_area function is defined with its parameters and return type specified in the comments. The multi-line comment provides clear instructions on how to use the function and what to expect from it.

By using triple quotes, you can include as much detail as necessary within the comment. This includes information about the purpose of the function, explanations of parameters, data types, and any other relevant details. It serves as both documentation for other developers and a reminder for yourself when revisiting the code in the future.

To access the docstring of a function, you can use the __doc__ attribute, like so:


Executing the above code will display the function's docstring, allowing you or other developers to read and understand its purpose and usage.

It's important to note that while docstrings are not mandatory for every function, they are considered good practice as they promote code readability, maintainability, and collaboration within a project. Following a consistent style for docstrings, such as adhering to the conventions outlined in the Python docstring conventions (PEP 257), can further enhance code documentation and readability.

How to See Docstrings in Visual Studio Code

Using Visual Studio Code's built-in tools

  1. Open Visual Studio Code and navigate to the Python file containing the function you want to inspect.
  2. Ensure that you have the Python extension installed and activated in Visual Studio Code. You can install the Python extension from the Visual Studio Code marketplace if you haven't already.
  3. Place your cursor on the function name within your code.
  4. Press Ctrl (or Cmd on macOS) and click on the function name. This action will take you to the definition of the function.
  5. Once you're on the definition of the function, move your cursor inside the function and press F1 to open the command palette.
  6. In the command palette, type "Python: Show Documentation" and select the corresponding option when it appears.

Visual Studio Code will display the docstring of the function in a separate window or panel, providing you with detailed information about the function's purpose, parameters, and return values.

Using the Python help() function

Alternatively, you can use the help() function directly in the Python interactive terminal within Visual Studio Code. Follow these steps:

  1. Open Visual Studio Code and open the Python file containing the function you want to inspect.
  2. Open the integrated terminal by selecting "View" from the menu, then "Terminal," and finally "New Terminal."
  3. In the terminal, type python to start the Python interactive mode.
  4. Import the module or file containing the function by typing import module_name or from module_name import function_name respectively.
  5. Type help(function_name) and press Enter. Replace function_name with the name of the function you want to inspect.
  6. The help() function will display the docstring of the function in the terminal, providing you with the relevant information.

Using help() in Visual Studio Code allows you to access the docstrings conveniently, providing you with valuable information about the functions and modules you are working with. It is a useful tool for understanding the purpose and usage of different Python constructs and enhancing your development process.

Best Practices for Commenting Code

To maximize the effectiveness of your code comments, consider the following best practices:

Be Clear and Concise

Ensure your comments are clear, concise, and to the point. Use plain language and avoid unnecessary technical jargon. Aim to provide valuable information without overwhelming the reader.

Explain the Why, Not the What

Instead of stating the obvious, focus on explaining the rationale behind certain decisions or the intention of a particular code block. This helps readers understand the purpose and context, enabling them to make informed modifications if necessary.

Update Comments Regularly

As your code evolves, make sure to update and maintain your comments accordingly. Outdated or inaccurate comments can be misleading and cause confusion.

Avoid Redundant Comments

Strive to write comments that add value and provide additional insights. Avoid duplicating information that is already evident from the code itself. Use comments to explain complex logic, algorithms, or any non-obvious implementation details.

Follow PEP 8 Guidelines

PEP 8, the official Python style guide, offers recommendations for commenting style and conventions. Adhering to these guidelines ensures consistency across your codebase and makes it easier for others to understand and contribute to your project. You can refer to the PEP 8 documentation for specific recommendations on commenting.

Commenting code in Python is a powerful practice that significantly improves code readability, maintainability, and collaboration. By adding appropriate comments, you provide valuable insights into your code logic, explain complex algorithms or business rules, and document the purpose and functionality of different parts of your code. Comments serve as annotations within your code that are not executed by the interpreter or compiler, but they provide important information for developers who read and work with the code.