How to Comment in Python

What you’ll build or solve

You’ll add clear single-line comments, use inline comments only when they add value, and write docstrings that tools can read.

When this approach works best

This approach works best when you:

  • Need to explain why you made a choice, such as a tradeoff or constraint.
  • Share code with other people, or plan to revisit it weeks later.
  • Build functions, classes, or modules that deserve usage notes and examples.

Skip comments when:

  • A comment would simply repeat the code. Rename variables or extract a function instead.

Prerequisites

  • Any Python version
  • A code editor

Step-by-step instructions

1) Add single-line comments with # to explain intent

Use # for short notes that clarify decisions, assumptions, or edge cases.

# Use UTC to avoid timezone bugs in logs
timestamp=datetime.utcnow()

Comments also work inside blocks:

foriteminitems:
# Skip empty values from user input
ifnotitem:
continue

What to look for

  • Use a space after #.
  • Align comments with the code they describe.
  • Prefer “why” comments over “what” comments.

2) Use inline comments only when they add information

Inline comments work best for short context that doesn’t fit cleanly in a variable name.

timeout=10# seconds, matches server keepalive

If the line feels crowded, move the comment above the code.

What to look for

Keep comments that add context the code can’t carry. Remove comments that simply restate the line.


3) Write docstrings for modules, functions, and classes

Docstrings use triple quotes and describe how to use a module, function, or class. Place them immediately under the definition so tools can find them.

Module docstring at the top of a file:

"""
Helpers for reading a JSON config file and validating required fields.
"""

Function docstring that explains behavior and errors:

defparse_user_id(value:str) ->int:
"""Convert a user ID string to a positive integer.

    Raises ValueError if the input is not a valid positive integer.
    """
user_id=int(value)
ifuser_id<=0:
raiseValueError("User ID must be positive")
returnuser_id

Class docstring that explains what the class represents:

classRateLimiter:
"""Limit requests to N actions per minute for a single key."""

What to look for

  • Put docstrings directly under def, class, or at the top of the file.
  • Use docstrings for “how to use this,” not for inline implementation details.

4) Prefer refactoring over extra comments

Comments can’t fix an unclear structure. If you feel tempted to explain a complex condition, a well-named helper function is often clearer than a long comment.

Before:

ifuseranduser.is_activeanduser.emailand"@"inuser.email:
send_welcome_email(user.email)

After:

defcan_receive_email(user) ->bool:
returnbool(useranduser.is_activeanduser.emailand"@"inuser.email)

ifcan_receive_email(user):
send_welcome_email(user.email)

What to look for

If you’re writing a comment to explain a long condition, consider extracting a helper function or using a named boolean variable.


Examples you can copy

Example 1: Explain a tradeoff or constraint

# Keep retries low to avoid duplicate charges on flaky networks
max_retries=2

Example 2: Inline comment that adds real context

page_size=100# API max per request

Example 3: Docstring that helps someone call your function

defformat_price(cents:int) ->str:
"""Format an integer price (in cents) as a currency string."""
returnf"${cents/100:.2f}"

Common mistakes and how to fix them

Mistake 1: Writing comments that restate the code

You might write:

# Set the user name
user_name="Mina"

Fix

Remove the comment, or explain the reason behind the value or behavior:

user_name="Mina"# demo account used in screenshots

Mistake 2: Turning a comment into a wall of text

You might write a long multi-paragraph comment explaining behavior, edge cases, and usage.

Fix

Move usage details into a docstring and keep inline comments short:

defload_config(path:str) ->dict:
"""Load a JSON config file.

    Raises FileNotFoundError if the file does not exist.
    Raises ValueError if the JSON is invalid.
    """
    ...

Troubleshooting

If docstrings don’t show up in your editor’s hover help

Check placement. The docstring must be the first statement under the def or class.


If comments disagree with the code

Update or delete the comment. Prefer changing code to match the comment only when the comment reflects the correct intent.


If you need too many comments to explain a section

Refactor. Extract helpers, rename variables, or split the function into smaller parts.


If you’re unsure what to document in a docstring

Include three things:

  • What it does
  • What it returns
  • What errors it can raise

Quick recap

  • Use # comments to explain intent and decisions.
  • Use inline comments only when they add context that the code can’t carry.
  • Use docstrings for modules, functions, and classes so tools can read them.
  • Prefer refactoring over piling on comments.
  • Delete or update comments that no longer match the code.