Back to series
· 9 min read

Python Comments and Code Style


1. Why Comments and Code Style Are Needed

Python emphasizes code readability. Compared with complex syntax tricks, clear naming, reasonable structure, and consistent formatting often better reflect code quality.

Code style mainly addresses the following issues:

  • Readability: Helps developers quickly understand the intent of the code.
  • Maintainability: Reduces the probability of introducing errors when modifying code.
  • Collaboration: Ensures team members follow consistent coding habits.
  • Extensibility: Keeps the project clear as features grow.
  • Reviewability: Helps code review focus on business logic rather than formatting differences.

For example, the following two code snippets implement the same functionality:

def calc(a,b):
    x=a*0.08
    return a+x
def calculate_total_with_tax(price: float) -> float:
    """Calculate the total amount including tax."""
    tax = price * 0.08
    return price + tax

The second snippet reduces the cost of understanding through clear function names, variable names, type hints, and a docstring.

Code style is not about making code look neat; it is about making the intent of the code clearer.

2. Basic Syntax of Python Comments

Python uses # to denote a single-line comment.

When the interpreter executes code, it ignores the content of comments. Comments mainly serve the people who read and maintain the code.

2.1 Single-line comments

Use # to write a single-line comment:

# Calculate the product price
price = 100

# Calculate the tax
tax = price * 0.08

# Calculate the final price
total = price + tax

A single space is usually kept after #.

Recommended:

# Get user input
name = input("请输入姓名:")

Not recommended:

#Get user input
name = input("请输入姓名:")

2.2 End-of-line comments

Comments can be added at the end of a line of code:

timeout = 30  # Request timeout, in seconds

However, you should not add comments to every line of code.

Not recommended:

name = "Alice"  # User name
age = 20        # User age
score = 95      # User score

If a variable name already expresses its meaning, a repeated comment is of little value.

More importantly, explain information that cannot be seen directly from the code itself.

# Use a 30-second timeout to prevent external services from blocking requests for a long time
timeout = 30

2.3 Multi-line comments

Python does not have a separate multi-line comment syntax, but multiple # comments can be used consecutively:

# User login flow:
# 1. Get the username and password
# 2. Verify the user's identity
# 3. Create a login session
# 4. Return the authentication result

This approach is suitable for explaining complex logic, business rules, and algorithm steps.

Note that consecutive # comments are still multiple ordinary comments, not a special language construct.

2.4 Special Content in Comments

Comments can record:

  • Business rules.
  • Algorithm design rationale.
  • Compatibility handling.
  • Known limitations.
  • Temporary to-do items.
  • Important security precautions.

For example:

# TODO: Add caching later to reduce repeated queries
# FIXME: The current implementation does not handle network connection interruptions
# NOTE: Compatibility with the old API must be maintained here
# WARNING: Do not output user passwords in logs

TODO, FIXME, NOTE, and WARNING are not Python keywords; they are comment tags agreed upon by the development team.

3. Docstrings

A docstring is a special string in Python used to describe a module, class, or function.

It is usually written with triple quotes and placed as the first statement after a module, class, or function definition.

Unlike ordinary comments, a docstring is stored in the object's __doc__ attribute and can be read by programs, IDEs, help systems, and documentation generation tools.

3.1 Function docstrings

def calculate_area(width: float, height: float) -> float:
    """Calculate the area of a rectangle.

    Args:
        width: Rectangle width.
        height: Rectangle height.

    Returns:
        Rectangle area.
    """
    return width * height

You can view a function's documentation with help():

help(calculate_area)

You can also access it directly:

print(calculate_area.__doc__)

3.2 Class Docstrings

A class docstring should explain the class's responsibilities, its purpose, and any important constraints.

class User:
    """Represents a user in the system.

    Attributes:
        username: The username.
        email: The user's email address.
    """

    def __init__(self, username: str, email: str):
        self.username = username
        self.email = email

3.3 Module Docstrings

A module docstring is usually placed at the very top of a Python file.

"""User management module.

Provides functionality for creating, querying, and updating users.
"""

def create_user(username: str):
    """Create a user."""
    return {"username": username}

A module docstring helps developers quickly understand the responsibilities of the entire file.

3.4 The Difference Between Docstrings and Regular Comments

Comparison dimension Regular comment Docstring
Syntax # A string, usually using triple quotes
Primary purpose Explain the code implementation Describe modules, classes, and functions
Retained in the object No Yes
Viewable via help() No Yes
Suitable for generating API documentation Usually not used directly Yes
Participates in program execution No Retained as the object's documentation

Note that triple quotes alone do not necessarily mean a docstring. Only when placed as the first statement following a module, class, or function definition will Python recognize it as that object's docstring.

4. How to Write High-Quality Comments

The core value of a comment is to explain the intent behind the code, not to repeat information the code already expresses.

4.1 Explain Why, Not Just What

Not recommended:

# Add 1 to the age
age += 1

Recommended:

# Update the account age after the user confirms their birthday
age += 1

The second version explains the business context.

4.2 Comments Should Stay in Sync with the Code

An outdated comment is more dangerous than no comment at all, because it can mislead maintainers.

For example:

# The user's age must be greater than 18
if age >= 21:
    allow_access = True

The comment and the code clearly disagree.

It should be corrected promptly:

# The user's age must be at least 21
if age >= 21:
    allow_access = True

4.3 Don't Use Comments to Cover Up Bad Code

Not recommended:

# Check whether the user is valid
if u is not None and u.a and u.s == 1:
    pass

Better:

def is_active_user(user) -> bool:
    return (
        user is not None
        and user.age > 0
        and user.status == 1
    )

Let the code itself express the intent through clear function and variable names.

4.4 Comments Should Record Important Constraints

Some code may not look intuitive, but there may be an important reason behind it.

# Must be stored in UTC to avoid skew when comparing across time zones
created_at = datetime.now(timezone.utc)

Comments like this help later developers avoid breaking a critical design decision.

5. Python Naming Conventions

Naming is an important part of code readability.

The Python community widely adopts PEP 8 as its code style reference, and it offers clear recommendations for different kinds of names.

5.1 Naming Variables

Variables and functions normally use lowercase letters, with words separated by underscores.

This style is called snake_case.

Recommended:

user_name = "Alice"
total_price = 199.9
is_active = True

Not recommended:

userName = "Alice"
TotalPrice = 199.9
isActive = True

Variable names should reflect actual meaning and avoid meaningless abbreviations.

5.2 Naming Functions

Functions usually use a verb or verb phrase that describes the action the function performs.

def get_user():
    pass


def calculate_total():
    pass


def validate_password():
    pass


def send_email():
    pass

Recommended conventions:

  • get_: retrieve data.
  • set_: set data.
  • is_: check a state.
  • has_: check whether something has a certain attribute.
  • create_: create an object.
  • delete_: delete an object.
  • validate_: validate data.

These are naming conventions, not mandatory language rules.

5.3 Class Naming

Class names typically use PascalCase, meaning each word starts with a capital letter and words are not separated by underscores.

class User:
    pass


class UserService:
    pass


class DatabaseConnection:
    pass

Not recommended:

class user_service:
    pass

5.4 Constant Naming

Constants typically use all-uppercase letters, with multiple words separated by underscores.

MAX_RETRY_COUNT = 3
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"

Python does not actually enforce that variables cannot be modified.

All-uppercase naming is only a convention, indicating that the developer intends the variable to be treated as a constant.

5.5 Special Naming Rules

Python also has some naming conventions with special meanings.

Naming Form Common Use Example
_name Convention indicating internal use _cache
name_ Avoid conflicts with keywords or other names class_
__name Name mangling mechanism in classes __password
__name__ Python special methods or special attributes __init__

Pay special attention to the following:

  • _name is only a convention indicating internal use; it is not real access control.
  • name_ is usually used to avoid conflicts with Python keywords.
  • __name triggers name mangling in class definitions, but it is not a true private attribute.
  • The __name__ form is generally reserved for special names defined by the Python language and should not be created casually.

VI. Code Layout and Formatting Conventions

Python uses indentation to denote code blocks, so code layout not only affects readability but also directly affects program syntax.

PEP 8 is the most common code style guide for Python.

6.1 Indentation

Using 4 spaces per indentation level is recommended.

def greet(name):
    if name:
        print(f"Hello, {name}")
    else:
        print("Hello, Guest")

Mixing tabs and spaces is not recommended.

def greet(name):
    print(f"Hello, {name}")

Although an editor may display mixed indentation correctly, different tools may handle indentation differently, which can easily trigger IndentationError or TabError.

6.2 Line Length

PEP 8's traditional recommendations for code line length are:

  • Regular code lines should not exceed 79 characters.
  • Comments and docstrings typically should not exceed 72 characters.

Real projects may choose a wider line width according to team conventions, such as 88 or 100 characters.

For example:

result = calculate_total(
    price=100,
    tax_rate=0.08,
    discount=10,
)

Do not sacrifice readability for the sake of keeping code on a single line.

6.3 Blank Lines

Using blank lines appropriately can separate different logical structures.

General recommendations:

  • Use two blank lines between top-level function and class definitions.
  • Use one blank line between method definitions within a class.
  • Use a suitable number of blank lines inside functions to group logic.
import math


def calculate_area(radius: float) -> float:
    """Calculate the area of a circle."""
    return math.pi * radius ** 2


def calculate_perimeter(radius: float) -> float:
    """Calculate the circumference of a circle."""
    return 2 * math.pi * radius

6.4 Operator Spacing

Generally, add spaces on both sides of binary operators.

Recommended:

total = price + tax
average = total / count

Not recommended:

total=price+tax
average=total/count

However, in scenarios such as function default parameters, the spacing rules differ:

def connect(host, port=8080):
    pass

Do not add spaces on either side of the = in default parameters.

If there is a type annotation:

def connect(host: str, port: int = 8080):
    pass

6.5 Parentheses and Collection Formatting

Use spaces appropriately to keep the structure clear.

numbers = [1, 2, 3]
user = {"name": "Alice", "age": 20}

result = (10 + 20) * 2

Usually add one space after a comma.

6.6 Import Statement Conventions

Import statements are usually placed at the top of the file and grouped in the following order:

  1. Standard library.
  2. Third-party libraries.
  3. Internal modules of the current project.

Use blank lines between different groups.

import json
import os
from pathlib import Path

import requests
from pydantic import BaseModel

from app.services.user_service import UserService

Prefer explicit imports:

from datetime import datetime

Try to avoid:

from datetime import *

Wildcard imports can easily cause naming conflicts and also reduce code readability.

7. PEP 8: The Official Python Style Guide

PEP stands for Python Enhancement Proposal.

PEP 8 is a code style guide widely adopted by the Python community; it sets out recommendations for code layout, naming, spacing, comments, imports, and other aspects.

Official documentation:

https://peps.python.org/pep-0008/

7.1 Main Guidelines of PEP 8

Guideline Category Main Recommendation
Indentation Use 4 spaces
Variable naming snake_case
Function naming snake_case
Class naming PascalCase
Constant naming UPPER_CASE
Imports Place at the top of the file and group them
Spacing Use operator spacing appropriately
Line length Traditionally, regular code lines are recommended not to exceed 79 characters
Comments Keep consistent with the code and express the actual intent
Blank lines Separate module, class, and function structures

7.2 PEP 8 Is Not a Syntax Rule

PEP 8 is primarily a set of coding style recommendations, not syntax rules that the Python interpreter must enforce.

For example:

userName = "Alice"

Although it does not follow common PEP 8 naming conventions, it is still valid Python code.

This means:

  • Syntactically correct does not mean stylistically compliant.
  • Nonconforming style does not necessarily mean the program will run incorrectly.
  • Teams can formulate their own supplementary conventions on top of PEP 8.

Most importantly, be consistent.

8. Python Type Hints and Code Readability

Type hints are used to specify the expected types of variables, parameters, and return values.

Python is a dynamically typed language. Type hints are generally not automatically enforced at runtime, but they can help IDEs, static analysis tools, and developers understand the code.

8.1 Variable Type Hints

name: str = "Alice"
age: int = 20
price: float = 99.9
is_active: bool = True

8.2 Function Parameter and Return Value Types

def calculate_total(
    price: float,
    quantity: int,
) -> float:
    return price * quantity

Type hints make a function's inputs and outputs clearer.

8.3 Container Type Hints

users: list[str] = ["Alice", "Bob"]

scores: dict[str, int] = {
    "Alice": 95,
    "Bob": 88,
}

Python 3.9 and later support built-in generic forms such as list[str] and dict[str, int] directly.

8.4 Optional Types

If a variable may be of a certain type or may be None, you can use a union type.

def find_user(user_id: int) -> str | None:
    if user_id == 1:
        return "Alice"

    return None

str | None means the return value may be a string or None.

In versions before Python 3.10, you can use:

from typing import Optional


def find_user(user_id: int) -> Optional[str]:
    return "Alice" if user_id == 1 else None

8.5 The Value of Type Hints

Type hints mainly provide the following benefits:

  • Improve code readability.
  • Provide IDE autocompletion.
  • Catch some type errors early.
  • Improve interface design.
  • Provide clearer contracts for large projects.

Common static type checking tools include:

  • mypy
  • Pyright
  • basedpyright

Type hints are not a runtime data validation mechanism. Data from network requests, user input, or external files still needs actual validation.

9. Code Style and Automation Tools

As projects grow larger, relying solely on manual code style checks becomes inefficient.

Automation tools help teams standardize formatting, find problems, and run static checks.

9.1 Ruff: Code Checking and Formatting

Ruff is a high-performance Python tool that can perform code checking (Linting) and code formatting (Formatting).

Install:

python -m pip install ruff

Check code:

ruff check .

Automatically fix some issues:

ruff check . --fix

Format code:

ruff format .

Check formatting without modifying files:

ruff format . --check

Ruff covers a large number of common code style and quality rules.

9.2 Black: Code Formatting

Black is a commonly used automatic formatting tool in the Python community.

Install:

python -m pip install black

Format:

black .

Check formatting:

black --check .

Black emphasizes consistent formatting results and reduces formatting disputes among team members.

9.3 Flake8: Code Style Checking

Flake8 is a common Python code checking tool that can check:

  • PEP 8 style issues.
  • Some syntax and code structure issues.
  • Some unused variable and import issues.

Install:

python -m pip install flake8

Run:

flake8 .

9.4 isort: Import Sorting

isort is used to automatically organize Python import statements.

Install:

python -m pip install isort

Run:

isort .

9.5 mypy: Static Type Checking

mypy can check for some type errors based on type hints.

Install:

```bash python -m pip install mypy ```

Run:

```bash mypy . ```

9.6 Tool Selection Recommendations

Tool Primary Responsibility Typical Command
Ruff Linting and formatting ruff check .
Black Code formatting black .
Flake8 Code style and quality checks flake8 .
isort Import sorting isort .
mypy Static type checking mypy .
Pyright Static type checking pyright

For new projects, you can prioritize Ruff, centralizing linting and formatting to reduce duplicated configuration across tools.

If a project already uses tools such as Black and isort, it can also continue with its existing setup.

10. Using pyproject.toml for Unified Configuration

pyproject.toml is a configuration file commonly used in modern Python projects, and it can centrally manage project metadata, build configuration, and tool settings.

For example:

```toml [tool.ruff] line-length = 88 target-version = "py312" [tool.ruff.lint] select = ["E", "F", "I", "UP", "B"] [tool.ruff.format] quote-style = "double" indent-style = "space" [tool.mypy] python_version = "3.12" strict = true ```

Configuration notes:

  • line-length: sets the code line length.
  • target-version: specifies the target Python version.
  • select: enables the specified lint rules.
  • quote-style: unifies the string quote style.
  • indent-style: specifies the indentation style.
  • strict: enables mypy's strict checking mode.

Note that Ruff and mypy each define their configuration fields differently; you cannot treat one tool's configuration options directly as another tool's options.

A project can add rules gradually according to its actual scale; there is no need to enable all strict checks from the very beginning.

11. Commenting Practices in Python Projects

In real projects, comments should serve business logic, interface design, and complex implementations, rather than becoming decoration for the code.

11.1 Ordinary Business Code

```python def calculate_discount(price: float, rate: float) -> float: """Calculate the discount amount based on the discount rate. Args: price: Original price of the product. rate: Discount rate, ranging from 0 to 1. Returns: The discount amount. """ if price < 0: raise ValueError("Product price cannot be negative") if not 0 <= rate <= 1: raise ValueError("Discount rate must be between 0 and 1") return price * rate ```

11.2 Complex Business Rules

```python def calculate_shipping_fee(weight: float) -> float: """Calculate the shipping fee based on the product weight.""" # The first 1 kg is the base weight; the excess is charged at 2 yuan per kg if weight <= 1: return 8.0 extra_weight = weight - 1 return 8.0 + extra_weight * 2 ```

The comment explains the billing rule, so maintainers do not have to infer the business meaning from the code alone.

11.3 Exception Handling Comments