如何按照PEP8规范为代码添加注释?
How to Write PEP8-Compliant Code Comments
Hey there! Let’s dive into writing code comments that follow PEP8 standards—because well-structured, compliant comments don’t just make your code look clean, they make it way easier for you (and other devs) to understand and maintain later. I’ll break this down into two parts to match your questions: first, the core rules for writing comments per PEP8, and second, practical ways to add these comments to your already PEP8-compliant code.
Part 1: PEP8 Rules for Writing Comments
PEP8 lays out clear guidelines for three main types of comments—let’s go through each:
Single-Line Comments
- Always place single-line comments on a separate line above the code they explain (inline comments are only okay if absolutely necessary, and even then, leave two spaces after the code before the
#). - Add a single space after the
#to separate the comment marker from your text. - Keep comments concise—focus on explaining why you did something, not what the code does (the code itself should make the "what" obvious).
Example:# Calculate monthly revenue by averaging daily totals (avoids skewed weekly peaks) monthly_revenue = sum(daily_revenues) / len(daily_revenues)
Block Comments
- Use block comments for longer explanations that span multiple lines.
- Each line in the block starts with a
#followed by a single space. - Indent the block to match the indentation level of the code it’s describing.
- Leave a blank line before the block comment to separate it from the surrounding code.
Example:# We're using linear search instead of binary here because the dataset # is small (<100 items) and binary search would add unnecessary overhead. # Linear search is simpler to read and maintain for this use case. for item in small_dataset: if item == target: return item
Docstrings (Documentation Strings)
- Docstrings are special comments used to document modules, classes, functions, and methods—they’re enclosed in triple quotes (
"""or'''). - Always include a docstring for public modules, classes, functions, and methods.
- For functions/methods, docstrings should typically include:
- A brief one-line summary of what the function does.
- Details about parameters (name, type, purpose).
- Return value type and description.
- Any exceptions raised.
Example:
def calculate_discount(price: float, discount_percent: float) -> float: """Calculate the discounted price after applying a percentage discount. Args: price: Original price of the item (must be non-negative). discount_percent: Discount percentage to apply (0-100). Returns: Discounted price as a float. Raises: ValueError: If price is negative or discount_percent is outside 0-100. """ if price < 0: raise ValueError("Price cannot be negative") if not 0 <= discount_percent <= 100: raise ValueError("Discount percent must be between 0 and 100") return price * (1 - discount_percent / 100)
Part 2: Adding PEP8-Compliant Comments to Your Code
Now that you know the rules, here’s how to apply them to your existing PEP8-compliant code:
- Start with docstrings first: For every public function, class, and module, add a clear docstring. Even if you think the code is "obvious," future you (or another dev) will thank you for the context.
- Flag non-intuitive logic: If you have a piece of code that uses a tricky workaround, non-standard approach, or solves an edge case, add a single-line or block comment explaining the reasoning.
Example:# Skip weekends since payment processing is unavailable if transaction_date.weekday() >= 5: continue - Use TODO comments for unfinished work: PEP8 recommends formatting TODO comments with
# TODO: [description]so tools can easily pick them up. Include context like who’s assigned or when it needs to be done if relevant.
Example:# TODO: Replace hardcoded API key with environment variable (tracked in ticket #123) api_key = "abc123xyz" - Avoid redundant comments: Don’t comment code that’s self-explanatory. For example,
# Increment counterabovecounter += 1is unnecessary—save comments for the "why," not the "what." - Keep comments up to date: If you change the code, make sure to update the corresponding comments. Outdated comments are worse than no comments at all!
内容的提问来源于stack exchange,提问作者plasticGlasses
相关产品推荐
相关产品推荐

