Writing Style Guide for Comments

In Python programming, comments serve as the critical bridge connecting human thought to machine execution. Although compilers or interpreters completely ignore the presence of comments and do not treat them as part of syntax errors, they are essential for maintaining code readability, conveying design intent, and reducing collaboration costs. Excellent comments should not merely repeat the functionality of the code (e.g., writing "calculates the sum" after x = y + z); instead, they should reveal hidden business logic, complex algorithmic steps, or strategies for handling special edge cases.
To ensure the effectiveness of comments, a set of strict writing guidelines and core principles must be followed:

  • Avoid Redundancy: If the code itself clearly expresses the intent (e.g., count = len(users)), no additional explanatory comment is needed; conversely, if the logic is obscure or involves complex algorithmic derivations, detailed explanations are mandatory.
  • Keep Dynamically Updated: Comments are static text, while code is dynamically evolving. Once business rules change, function signatures adjust, or dependency libraries upgrade causing changes in original logic, corresponding comments must be synchronized to reflect the latest state.
  • Focus on "Why" rather than "What": Do not spend笔墨 explaining what a variable name like total represents (this is determined by naming conventions); instead, focus on why an accumulation strategy was chosen here, how empty value boundary conditions are handled, or the logic for capturing specific exceptions.

Syntax Structure and Application Scenarios of Python Comments

Python provides two primary forms of comments, each suitable for different levels and purposes: single-line comments are used for brief explanations, while multi-line docstrings are used to define behavioral contracts for functions, classes, and modules.

1. Application of Single-Line Comments

Single-line comments start with the hash symbol # and are typically used on the same line immediately following the relevant code line. They are best suited for explaining temporary variable meanings or the basis of complex single-step logical judgments:

# When calculating user balance, prioritize deducting fees before executing transfer operations
def transfer_balance(user_id, amount):
    fee = calculate_fee(amount) * TAX_RATE
    
    # If account balance is insufficient and credit line is not enabled, reject transaction request
    if user.balance < (amount + fee) and not has_credit_line(user.id):
        raise InsufficientFundsError("Insufficient funds to cover principal and fees")

    return update_balance(user_id, -1 * amount)

2. Guidelines for Docstrings

For functions, classes, and methods, it is recommended to wrap multi-line text with triple quotes """ or ''' to form a Docstring. This not only complies with the PEP 8 style guide requirements but also serves as the foundational data source for automatically generating API documentation and IDE intelligent hints:

def parse_json_data(json_string, encoding='utf-8'):
    """
    Parse a JSON formatted string into a Python dictionary object.
    
    :param json_string: The raw JSON text to be parsed; must be a non-empty string.
    :type json_string: str
    
    :param encoding: Specify the character encoding format; default is utf-8.
    :type encoding: str, optional
    
    :return: The converted Python dict object or None (when input is empty).
    :rtype: dict | None

    :raises ValueError: Raises an exception when JSON syntax structure is incorrect.
    
    **Example**:
        >>> data = '{"name": "Alice", "age": 30}'
        >>> result, error = parse_json_data(data)
        >>> print(result['name']) 
        Alice
    """
    if not json_string:
        return None
    
    try:
        # Attempt to parse, catching format errors and handling them uniformly
        parsed_obj = json.loads(json_string, encoding=encoding)
        validate_structure(parsed_obj)
        return parsed_obj
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON data: {e}") from e

def calculate_discount(price):
    """Calculate the final price after applying product discount."""

Comment Techniques and Precautions in Special Scenarios

In actual development, besides regular functional explanations, specific handling methods for certain scenarios must be noted:

  • TODO/FIXME/XXX Markers: When code contains pending tasks, known defects, or logic requiring future optimization, markers such as # TODO: ..., # FIXME: (indicating a bug that must be fixed) should be used as prefixes. These comments act as signal lights for project management, reminding developers to pay attention to legacy issues, but there must be a clear distinction between "planned" and "confirmed errors".
  • Handling Magic Numbers: It is strictly prohibited to use undefined numeric constants in code (e.g., if x > 100:). All numbers with business meaning must be defined as named constants, with comments added above them explaining the source or calculation basis. For example, change 100 to MAX_RETRY_COUNT = 3 and attach a comment indicating "Maximum retry count limit".
  • Cross-Language/Multi-Team Collaboration: If the project involves maintenance by non-Python developers (e.g., frontend, operations), ensure that key logic provides plain business descriptions in comments, avoiding over-reliance on technical terms or internal abbreviations.

Conclusion and Best Practice Summary

Writing high-quality code comments is a technical soft skill that requires continuous investment. It demands that authors possess a global perspective during the coding phase, able to anticipate future modification needs and plan document structures in advance. By strictly adhering to the above guidelines, using single-line comments to explain details, Docstrings to define contracts, and special markers to highlight risks, maintenance costs can be significantly reduced, and overall team development efficiency and code quality levels can be improved. Remember, good comments are not a restraint on readers but a gift for future selves and respect for collaboration partners.