DEV Community

Cover image for The Secret Art of Writing Great Python Comments
Aaron Rose
Aaron Rose

Posted on

The Secret Art of Writing Great Python Comments

So, you know how to write a Python comment. You’ve mastered the # and the """. But there’s a vast difference between a comment that’s just there and one that’s genuinely useful.

Writing great comments is an art. It’s about striking the perfect balance between clarity and clutter. Let's move beyond the basics and learn the secrets of writing comments that other developers will thank you for.

1. The PEP 8 Guidelines: More Than Just Suggestions

PEP 8 is Python’s official style guide. While it’s not law, following it makes your code look professional and consistent. Here’s what it says about comments:

  • Inline Comments: Use them sparingly. Most importantly, separate them from the statement by at least two spaces. The # should be followed by a single space and then the comment itself.

    # 😕 Bad (no space after the #, no space before)
    x=5#initialize x
    
    # 😕 Mediocre (missing at least two spaces *before* and a space *after* the #)
    x = 5# initialize x
    
    # ✅ Good (PEP 8 compliant: two+ spaces before, one space after #)
    x = 5  # Initialize the counter variable
    
  • Block Comments: Each line of a block comment should start with a # and a single space. Paragraphs within the block are separated by a line containing a single #.

    # 😕 Bad (no space after #, hard to read)
    #This function does a thing
    #it's really complicated
    
    # ✅ Good (PEP 8 compliant)
    # This function validates the user input against the database
    # and applies a series of data-cleaning rules. It is designed
    # to be fault-tolerant.
    #
    # Returns a cleaned string or None if validation fails.
    

2. The Hall of Fame: Examples of Truly Great Comments

Great comments are like a code archaeologist's tool, unearthing the hidden reasons and decisions behind the code. They explain things that aren't visible in the code itself.

✅ Explaining the "Why" Behind a Workaround:

# Using a list comprehension here instead of a generator because
# we need to iterate over the result multiple times to validate it.
data = [process(item) for item in large_dataset]
Enter fullscreen mode Exit fullscreen mode

✅ Warning Future Developers:

# WARNING: Changing this constant will break the external API integration.
# The third-party system expects this exact key name. See ticket DEV-445.
API_RESPONSE_KEY = "External-ID"
Enter fullscreen mode Exit fullscreen mode

✅ Clarifying Complex Business Logic:

# The discount is capped at 50% for 'SUPER_SALE' events, but
# management has approved a 60% cap for user tier 'PLATINUM'.
# (Email approval from CMO, 2023-10-26)
if user_tier == 'PLATINUM':
    discount = min(discount, 0.6)
else:
    discount = min(discount, 0.5)
Enter fullscreen mode Exit fullscreen mode

3. The Hall of Shame: Comments You Should Avoid

Just as important as writing good comments is knowing what not to write.

❌ The Liar (Outdated Comment):
This is the most dangerous comment. It actively misleads anyone reading the code.

# This function returns a list of strings
def get_user_data(): 
    # ... code was changed later to return a dictionary ...
    return {'name': 'Alice', 'id': 12345}  # Comment is now a lie!
Enter fullscreen mode Exit fullscreen mode

Pro Tip: Make a habit of updating comments as soon as you change the code they refer to. An outdated comment is often worse than no comment at all.

❌ The Obvious (No Value Added):
This just adds visual noise.

# Set the value of x to 10
x = 10

# Loop through the list
for item in my_list:
    # Print the item
    print(item)
Enter fullscreen mode Exit fullscreen mode

❌ The Journal (Commented-Out Code):
This is what version control (like Git) is for. Delete it!

# old_code()
# if condition:
#     do_something_else()
new_code()
Enter fullscreen mode Exit fullscreen mode

4. The Pro's Checklist: Does Your Comment Earn Its Keep?

Before you write a comment, give it the quick "3 S" test:

  1. Is it SPOT-ON? Does it explain why, not just what? Does it provide context that isn't obvious from the code?
  2. Is it SUCCINCT? Is it concise and to the point? Could it be shorter without losing meaning?
  3. Is it SMART? If the code changes, will this comment need to be updated? If yes, is the value worth the maintenance cost?

If you can answer "yes" to these, you've written a great comment.

The Takeaway

Great comments don't just describe code; they illuminate it. They are the sign of a developer who thinks not just about making the code work, but about making it understandable.

Master this art, and you’ll quickly become the most valued developer on any team.


Next Step: Ready to make your code self-documenting? In our next post, we’ll unlock the full power of Docstrings and show you how to generate beautiful documentation automatically.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.