Commenting the Why Instead of the What

🏷️ Python Scripting Best Practices / Meaningful Comments and Docstrings

🧭 Context Introduction

When you're new to Python, it's tempting to write comments that simply describe what the code is doing. For example, you might write # This adds 1 to the counter right before a line like counter += 1. While this isn't wrong, it doesn't add much valueβ€”the code itself already tells you what it does. The real power of comments lies in explaining why the code exists, why it's written a certain way, or why a particular approach was chosen over another. This helps you and your teammates understand the reasoning behind decisions, especially when revisiting code weeks or months later.


πŸ•΅οΈ The Core Principle: Why Over What

  • What comments describe the obvious. They restate the code in plain English and often clutter the script without adding insight.
  • Why comments explain the intent, the business logic, the constraints, or the edge cases that drove the implementation.

πŸ’‘ Key Insight: If someone can understand the "what" by reading the code itself, you don't need a comment for it. Reserve comments for the "why" that isn't obvious from the code alone.


βš™οΈ Example: What vs. Why

❌ What Comment (Avoid) βœ… Why Comment (Preferred)
# Multiply by 2
result = value * 2
# Double the value because the API expects the result in cents
result = value * 2
# Set timeout to 30
timeout = 30
# Use 30-second timeout to match the upstream service's SLA
timeout = 30
# Check if user exists
if user_id in database:
# Avoid duplicate registration; the business rule requires unique user IDs
if user_id in database:

πŸ› οΈ When to Write a "Why" Comment

  • Business rules or domain logic: Explain why a specific value, threshold, or condition is used.
  • Workarounds or known issues: If you're coding around a bug in a library or an API limitation, document it.
  • Performance decisions: If you chose a slower but safer approach, or a faster but riskier one, explain the trade-off.
  • Non-obvious dependencies: When the code relies on an external system's behavior, configuration, or version.
  • Historical context: If a previous approach failed or a requirement changed, a brief note saves future confusion.

πŸ“Š Common Pitfalls to Avoid

  • Over-commenting: Too many comments can make the code harder to read. Only comment when the "why" isn't obvious.
  • Outdated comments: If you change the code, update the comment. A misleading comment is worse than no comment.
  • Obvious comments: Avoid comments that simply repeat the code. Trust that your teammates can read Python.
  • Commenting dead code: Don't leave commented-out code lying around. Delete it or add a clear reason if it must stay temporarily.

πŸ§ͺ A Practical Example

Consider this snippet without meaningful comments:

if retry_count > 3: ** send_alert() ** return

Now with a "why" comment:

# Retry more than 3 times indicates a persistent failure; # alert the on-call team instead of blocking the pipeline if retry_count > 3: ** send_alert() ** return

The second version tells you why the threshold is 3 and why an alert is sent instead of continuing. This helps anyone reading the code understand the operational intent.


βœ… Summary Checklist

  • [ ] Does this comment explain something the code doesn't already show?
  • [ ] Would a teammate benefit from knowing the reasoning here?
  • [ ] Is the comment accurate and up to date with the current code?
  • [ ] Could I remove this comment and still understand the code later?

πŸ“Œ Final Thought

Great comments are not about documenting the obviousβ€”they're about capturing the context, constraints, and decisions that live behind the code. By focusing on the "why," you turn your comments into a valuable narrative that makes your Python scripts easier to maintain, debug, and extend.


This practice means writing comments that explain why code exists or makes a specific choice, not what the code does (which the code itself already shows).


πŸ“ Example 1: Explaining a Calculation Choice

This example shows a comment that explains why a specific formula is used, rather than restating the math.

# Use 1.60934 instead of 1.6 to match international aviation standards
miles = 10
kilometers = miles * 1.60934

πŸ“€ Output: 16.0934


πŸ“ Example 2: Explaining a Hardcoded Value

This example shows a comment that explains why a specific number is hardcoded, rather than describing what the variable holds.

# Maximum retries set to 3 because the external API times out after 3 attempts
max_retries = 3

πŸ“€ Output: 3


πŸ“ Example 3: Explaining a Conditional Logic Choice

This example shows a comment that explains why a condition is checked in a certain order, rather than describing the condition itself.

# Check for None first to avoid AttributeError on NoneType
data = None
if data is None:
    result = "No data available"
else:
    result = data.upper()

πŸ“€ Output: No data available


πŸ“ Example 4: Explaining a Workaround for a Known Bug

This example shows a comment that explains why a workaround exists, rather than describing what the workaround does.

# Sleep 2 seconds because the database replication lags by ~1.5 seconds
import time
time.sleep(2)
print("Data sync completed")

πŸ“€ Output: Data sync completed


πŸ“ Example 5: Explaining a Performance Trade-off

This example shows a comment that explains why a slower but safer approach is chosen, rather than describing the algorithm.

# Use simple loop instead of list comprehension for readability by junior engineers
temperatures = [72, 68, 75, 70]
adjusted = []
for temp in temperatures:
    adjusted.append(temp + 2)

πŸ“€ Output: [74, 70, 77, 72]


πŸ“ Example 6: Explaining a Business Rule

This example shows a comment that explains why a specific business rule is applied, rather than describing the code logic.

# Discount only for orders over $100 to match company policy from 2023
order_total = 150
if order_total > 100:
    discount = order_total * 0.10
else:
    discount = 0

πŸ“€ Output: 15.0


πŸ“ Example 7: Explaining a Configuration Choice

This example shows a comment that explains why a specific configuration value is chosen, rather than describing what the configuration does.

# Timeout set to 30 seconds because the slowest server responds in 25 seconds
timeout_seconds = 30

πŸ“€ Output: 30


Comparison Table

Comment Type What It Does Why It Matters
❌ Commenting the What # Multiply by 1.60934 Repeats code β€” adds no value
βœ… Commenting the Why # Use 1.60934 to match aviation standards Explains reasoning β€” helps future engineers understand decisions

🧭 Context Introduction

When you're new to Python, it's tempting to write comments that simply describe what the code is doing. For example, you might write # This adds 1 to the counter right before a line like counter += 1. While this isn't wrong, it doesn't add much valueβ€”the code itself already tells you what it does. The real power of comments lies in explaining why the code exists, why it's written a certain way, or why a particular approach was chosen over another. This helps you and your teammates understand the reasoning behind decisions, especially when revisiting code weeks or months later.


πŸ•΅οΈ The Core Principle: Why Over What

  • What comments describe the obvious. They restate the code in plain English and often clutter the script without adding insight.
  • Why comments explain the intent, the business logic, the constraints, or the edge cases that drove the implementation.

πŸ’‘ Key Insight: If someone can understand the "what" by reading the code itself, you don't need a comment for it. Reserve comments for the "why" that isn't obvious from the code alone.


βš™οΈ Example: What vs. Why

❌ What Comment (Avoid) βœ… Why Comment (Preferred)
# Multiply by 2
result = value * 2
# Double the value because the API expects the result in cents
result = value * 2
# Set timeout to 30
timeout = 30
# Use 30-second timeout to match the upstream service's SLA
timeout = 30
# Check if user exists
if user_id in database:
# Avoid duplicate registration; the business rule requires unique user IDs
if user_id in database:

πŸ› οΈ When to Write a "Why" Comment

  • Business rules or domain logic: Explain why a specific value, threshold, or condition is used.
  • Workarounds or known issues: If you're coding around a bug in a library or an API limitation, document it.
  • Performance decisions: If you chose a slower but safer approach, or a faster but riskier one, explain the trade-off.
  • Non-obvious dependencies: When the code relies on an external system's behavior, configuration, or version.
  • Historical context: If a previous approach failed or a requirement changed, a brief note saves future confusion.

πŸ“Š Common Pitfalls to Avoid

  • Over-commenting: Too many comments can make the code harder to read. Only comment when the "why" isn't obvious.
  • Outdated comments: If you change the code, update the comment. A misleading comment is worse than no comment.
  • Obvious comments: Avoid comments that simply repeat the code. Trust that your teammates can read Python.
  • Commenting dead code: Don't leave commented-out code lying around. Delete it or add a clear reason if it must stay temporarily.

πŸ§ͺ A Practical Example

Consider this snippet without meaningful comments:

if retry_count > 3: ** send_alert() ** return

Now with a "why" comment:

# Retry more than 3 times indicates a persistent failure; # alert the on-call team instead of blocking the pipeline if retry_count > 3: ** send_alert() ** return

The second version tells you why the threshold is 3 and why an alert is sent instead of continuing. This helps anyone reading the code understand the operational intent.


βœ… Summary Checklist

  • [ ] Does this comment explain something the code doesn't already show?
  • [ ] Would a teammate benefit from knowing the reasoning here?
  • [ ] Is the comment accurate and up to date with the current code?
  • [ ] Could I remove this comment and still understand the code later?

πŸ“Œ Final Thought

Great comments are not about documenting the obviousβ€”they're about capturing the context, constraints, and decisions that live behind the code. By focusing on the "why," you turn your comments into a valuable narrative that makes your Python scripts easier to maintain, debug, and extend.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

This practice means writing comments that explain why code exists or makes a specific choice, not what the code does (which the code itself already shows).


πŸ“ Example 1: Explaining a Calculation Choice

This example shows a comment that explains why a specific formula is used, rather than restating the math.

# Use 1.60934 instead of 1.6 to match international aviation standards
miles = 10
kilometers = miles * 1.60934

πŸ“€ Output: 16.0934


πŸ“ Example 2: Explaining a Hardcoded Value

This example shows a comment that explains why a specific number is hardcoded, rather than describing what the variable holds.

# Maximum retries set to 3 because the external API times out after 3 attempts
max_retries = 3

πŸ“€ Output: 3


πŸ“ Example 3: Explaining a Conditional Logic Choice

This example shows a comment that explains why a condition is checked in a certain order, rather than describing the condition itself.

# Check for None first to avoid AttributeError on NoneType
data = None
if data is None:
    result = "No data available"
else:
    result = data.upper()

πŸ“€ Output: No data available


πŸ“ Example 4: Explaining a Workaround for a Known Bug

This example shows a comment that explains why a workaround exists, rather than describing what the workaround does.

# Sleep 2 seconds because the database replication lags by ~1.5 seconds
import time
time.sleep(2)
print("Data sync completed")

πŸ“€ Output: Data sync completed


πŸ“ Example 5: Explaining a Performance Trade-off

This example shows a comment that explains why a slower but safer approach is chosen, rather than describing the algorithm.

# Use simple loop instead of list comprehension for readability by junior engineers
temperatures = [72, 68, 75, 70]
adjusted = []
for temp in temperatures:
    adjusted.append(temp + 2)

πŸ“€ Output: [74, 70, 77, 72]


πŸ“ Example 6: Explaining a Business Rule

This example shows a comment that explains why a specific business rule is applied, rather than describing the code logic.

# Discount only for orders over $100 to match company policy from 2023
order_total = 150
if order_total > 100:
    discount = order_total * 0.10
else:
    discount = 0

πŸ“€ Output: 15.0


πŸ“ Example 7: Explaining a Configuration Choice

This example shows a comment that explains why a specific configuration value is chosen, rather than describing what the configuration does.

# Timeout set to 30 seconds because the slowest server responds in 25 seconds
timeout_seconds = 30

πŸ“€ Output: 30


Comparison Table

Comment Type What It Does Why It Matters
❌ Commenting the What # Multiply by 1.60934 Repeats code β€” adds no value
βœ… Commenting the Why # Use 1.60934 to match aviation standards Explains reasoning β€” helps future engineers understand decisions