17  Comments

Comments are an essential part of any programming language. They are used to document code, provide explanations, and make the code more readable. They are ignored by the interpreter and are not executed as part of the program.

In this section, we will discuss the importance of comments in programming, the syntax for adding comments in Python, and general good practices for commenting in programming. We will also provide examples of good and bad practices for commenting in Python.

17.1 Why Use Comments?

Comments are essential for the following reasons:

  • Clarify Code: Comments help explain your code, making it easier to understand later or for others.
  • Reminders: Use comments to remind yourself why certain decisions were made in the code.
  • Debugging: Comments can help identify issues or bugs in the code.
  • Documentation: Comments serve as documentation for the codebase, explaining how it works and why certain choices were made.
  • Collaboration: Comments facilitate collaboration by allowing multiple developers to understand and work on the same codebase.
  • Maintenance: Comments make it easier to maintain and update code in the future.
  • Compliance: Comments can help ensure that code complies with standards and best practices.
  • Learning: Comments can be used as a learning tool for beginners to understand how code works.
  • Testing: Comments can be used to temporarily disable code for testing purposes.
  • Organization: Comments help organize code into logical sections and provide structure.
Figure 17.1: Code should ideally be self-explanatory, but comments can provide additional context and explanations for future reference.

17.2 Syntax for Comments in Python

In Python, comments are indicated by a hash (#) at the beginning of a line or after a statement. Comments can also be added at the end of a line of code (inline comments). The interpreter ignores everything after the hash symbol on a line, treating it as a comment. In Listing 17.1, we provide examples of single-line, inline, and multi-line comments in Python. Note that, if a hash symbol is used inside a string, it is treated as part of the text and not as a comment.

Listing 17.1: Example of single-line, inline, and multi-line comments in Python.
# This is a single-line comment

x = 5  # This is an inline comment

def greet(
    name: str,  # This is an inline comment
    age: int,  # This is another inline comment
):
    """
    This is a multi-line comment
    It spans multiple lines
    and provides additional context
    """
    print(f"Hello, {name}!")
)


msg = "Hello, #World"  # This is not a comment


'''
This is a multi-line comment using triple quotes.
It can span multiple lines and is treated as a string.
However, it is often used as a multi-line comment.
'''

"""
This is another multi-line comment using triple quotes.
It serves the same purpose as the previous example.
"""

17.3 General Good Practices

In the following sections, we will discuss general good practices for commenting in programming and provide examples of good and bad practices for commenting in Python.

17.3.1 1. Prioritize Clear Code Over Comments

  • Explanation: Write code that is clear and self-explanatory. If the code itself can be made clearer through better naming or structure, prioritize that over adding a comment to explain unclear code.

  • Bad Practice Example:

    # Increment the counter by 1
    i = i + 1
    • Why It’s Bad: The comment merely restates what the code is doing without adding any new information. Instead, the variable i could have a more descriptive name, like counter, to make the code self-explanatory.

17.3.2 2. Use Comments Sparingly

  • Explanation: Comments should be used only when they add value. Avoid adding comments that describe what the code does in a way that is redundant or unnecessary.

  • Bad Practice Example:

    # This line of code calculates the value of x
    x = calculate_value()
    • Why It’s Bad: The comment simply restates the obvious. The code itself is straightforward, and the comment doesn’t provide any additional insight.

17.3.3 3. Avoid Redundant and Misleading Comments

  • Explanation: Comments that restate the code or provide incorrect information can be confusing and should be avoided.

  • Bad Practice Example:

    # Subtracting 1 from the total
    total = total + 1
    • Why It’s Bad: The comment incorrectly describes the action performed by the code, which actually adds 1 to total. Misleading comments like this can lead to errors in understanding and maintaining the code.

17.3.4 4. Keep Comments Updated

  • Explanation: As code evolves, comments need to be updated to reflect the current state of the code. Outdated comments can mislead developers.

  • Bad Practice Example:

    # This code checks if the number is greater than 10
    if number < 5:
        print("Number is less than 5")
    • Why It’s Bad: The comment describes an old version of the code. The code now checks if the number is less than 5, not greater than 10. Failing to update the comment leads to confusion.

17.3.5 5. Use Comments for Intent and Rationale

  • Explanation: Comments should explain why certain decisions were made, especially if they are not immediately obvious from the code itself.

  • Bad Practice Example:

    # Special calculation
    result = x * y + z
    • Why It’s Bad: The comment does not explain the reason behind the calculation or why it’s “special.” Without context, future developers won’t understand the rationale behind the formula.

17.3.7 7. Avoid Commenting Out Code

  • Explanation: Instead of commenting out code, consider removing it if it’s no longer needed. Commented-out code can clutter your codebase and cause confusion.

  • Bad Practice Example:

    # Old approach
    # PRECISION = 0.00001
    # x = PRECISION * y
    • Why It’s Bad: This commented-out code adds clutter and can confuse future developers. If the old approach is no longer needed, it should be removed.

17.3.8 8. Minimize Noise Comments

  • Explanation: Avoid comments that add no value, such as those stating the obvious or repeating what the code already clearly conveys.

  • Bad Practice Example:

    # Declare an integer variable
    counter = 0
    • Why It’s Bad: The comment is unnecessary because the code is self-explanatory. It adds noise without providing any useful information.

17.3.9 9. Consider the Longevity of Comments

  • Explanation: Write comments that will remain relevant and useful over time. Ensure that they provide long-term value and aren’t likely to become outdated.

  • Bad Practice Example:

    # Temporary fix for bug
    x = y / (z + 0.00001) # Avoid division by zero
    • Why It’s Bad: The comment labels the code as a “temporary fix,” but without a plan to revisit and update the code, it could remain indefinitely, leading to potential issues down the line.

17.3.10 10. Use Descriptive Naming Over Comments

  • Explanation: Whenever possible, use descriptive names for variables, functions, and procedures to make the code self-documenting, reducing the need for comments.

  • Bad Practice Example:

    # Check if x is less than y
    if x < y:
        print("x is less than y")
    • Why It’s Bad: Instead of relying on the comment, renaming x and y to something more descriptive, like current_value and threshold, would make the code clearer without needing a comment.