Python Comments: Best Practices and Examples

Published on: July 10, 2026
Reading time: 6 minutes
2 balões de comentários em um fundo laranja

Python comments help readers understand decisions, constraints, and non-obvious behavior in source code. They are ignored by the interpreter, but they can make maintenance easier when they explain why the code exists instead of repeating what each line already says.

This guide covers single-line comments, inline comments, block explanations, TODO notes, type comments, shebangs, documentation, common mistakes, and practical standards for teams. You will also learn the difference between comments and docstrings and when clear code is better than another explanation.

Combine these practices with PEP 8, Python docstrings, and focused functions.

What Is a Python Comment?

A comment begins with the hash character:

# Calculate the final price after applying the discount.
final_price = subtotal - discount

Python ignores everything from # to the end of that physical line, except when the symbol appears inside a string.

The official Python lexical analysis reference defines comments. PEP 8’s comment section gives style recommendations.

Write a Single-Line Comment

# Request a new token before the current one expires.
refresh_token()

A good comment explains an intention or requirement that is not obvious from the code. It should be a complete, clear sentence when it describes a complete idea.

Avoid Repeating the Code

This comment adds no useful information:

# Add one to the counter.
counter += 1

A better comment explains the reason:

# Include the header row in the displayed line count.
counter += 1

Readers can already see the operation. They need context that the syntax cannot express.

Use Inline Comments Sparingly

timeout = 30  # Required by the partner API agreement.

An inline comment appears after code on the same line. It can be useful for a short constraint, unit, or special case. Leave enough spacing so it remains visually separate.

Avoid long inline explanations. Move them above the relevant block or improve the variable name.

Explain a Block of Code

Python has no dedicated block-comment syntax. Use consecutive comment lines:

# Normalize the address before comparing it with stored values.
# The external service may add spaces and uppercase characters.
normalized_email = email.strip().lower()

Do not use an unassigned triple-quoted string as a substitute for a comment. It creates a string literal rather than a true comment and may become a docstring in certain positions.

Comments vs Docstrings

A comment explains implementation details:

# Use a set because this loop performs thousands of membership checks.
allowed_ids = set(raw_ids)

A docstring explains a public interface:

def is_allowed(user_id: int) -> bool:
    """Return whether a user may access the resource."""
    return user_id in allowed_ids

Docstrings are available through help() and __doc__. Comments are visible only in the source. The docstrings guide explains modules, classes, functions, parameters, returns, and exceptions.

Prefer Clear Names

A comment should not repair a confusing name:

# Total number of active customers.
x = 42

Rename the variable:

active_customer_count = 42

Clear names reduce the amount of documentation required and remain accurate when code is moved.

Explain Why, Not What

# Round only for display; calculations keep the original precision.
displayed_total = round(total, 2)

The comment records an important design decision. Without it, a future developer might round earlier and change calculation results.

Document Workarounds

Temporary compatibility code needs context:

# Keep this conversion until the legacy endpoint returns numeric IDs.
customer_id = int(response_data["customer_id"])

A useful workaround comment states:

  • Why the workaround exists.
  • Which external behavior requires it.
  • What condition allows its removal.
  • Where additional context can be found.

Do not include private ticket URLs or sensitive information in public repositories.

Use TODO Comments with Context

# TODO: Replace the in-memory cache when the service supports Redis.
cache = {}

A bare # TODO is not actionable. State the desired change and the condition or reason. Teams may include an issue identifier when their workflow supports it.

FIXME and NOTE

# FIXME: This calculation fails when the reporting period crosses a year.

# NOTE: The provider limits this endpoint to 100 records per request.

Use markers consistently. A team should agree on whether these comments require linked issues, owners, or deadlines.

Comment Units and Formats

Units are a strong reason for a short comment when the name cannot carry all context:

request_timeout = 2.5  # Seconds.
max_file_size = 10 * 1024 * 1024  # Bytes.

Whenever possible, include the unit in the variable name:

request_timeout_seconds = 2.5

Explain Regular Expressions

import re

# Match an uppercase prefix, a hyphen, and exactly six digits.
product_code_pattern = re.compile(r"^[A-Z]+-\d{6}$")

Complex regular expressions are easier to maintain when their intention and expected examples are documented. The regex guide covers patterns, groups, flags, and validation.

Explain Non-Obvious Performance Choices

# Convert once because every event checks membership in this collection.
blocked_user_ids = set(blocked_user_ids_list)

for event in events:
    if event.user_id in blocked_user_ids:
        continue

The comment prevents someone from changing the set back to a list without understanding the performance reason.

Explain Security Decisions

# Compare tokens with a timing-resistant function.
if secrets.compare_digest(received_token, expected_token):
    grant_access()

Security comments should explain the protection without exposing credentials, internal defenses, or exploitable details.

Comment Public Examples Carefully

Comments inside tutorials should help learners connect syntax with intention:

prices = [10, 25, 8]

# Start at zero because no items have been processed yet.
total = 0

for price in prices:
    total += price

print(total)

As readers gain experience, remove comments that merely narrate basic syntax and keep the explanations that reveal design choices.

Shebang Lines

On Unix-like systems, a script may begin with a shebang:

#!/usr/bin/env python3

print("Hello")

This line is interpreted by the operating system when the file is executable. Python treats it as a comment. It is not required when the script is run with python script.py.

Encoding Declarations

Modern Python source files default to UTF-8. An encoding declaration is normally unnecessary, but Python recognizes a special comment near the beginning of a file:

# -*- coding: utf-8 -*-

Only use a different encoding when a real legacy requirement exists. UTF-8 is the preferred default for new source code.

Type Comments

Older or special code may use type comments:

items = []  # type: list[str]

Modern Python usually prefers annotations:

items: list[str] = []

The type hints guide explains annotations and static analysis.

Temporarily Commenting Out Code

Commenting out a line may help during a quick experiment:

load_data()
# send_email()
generate_report()

Do not leave large blocks of dead code in the repository. Version control already preserves history. Delete obsolete code and recover it from Git when necessary.

Comments in Conditional Logic

When a business rule is unusual, explain it near the condition:

# Trial accounts keep read access for seven days after expiration.
if account.is_trial and days_since_expiration <= 7:
    allow_read_only_access()

For complicated logic, extract a well-named function and add a docstring instead of surrounding a long condition with comments.

Keep Comments Updated

An outdated comment is dangerous because readers may trust it more than the code:

# Retry three times.
for attempt in range(5):
    send_request()

Update the comment in the same change that updates the behavior. During code review, verify comments just as carefully as executable lines.

Comments and Tests

A comment describing expected behavior is not a substitute for a test:

# The total should never be negative.
assert total >= 0

For a real invariant, validate or test it explicitly. The Pytest guide explains regression tests and exception checks.

Comments and Logging

Comments help developers reading source code. Logs help operators understand a running program. Do not replace runtime diagnostics with comments:

import logging

logging.info("Imported %s customer records", record_count)

The logging guide covers levels, formatting, files, and handlers.

Common Mistakes

  • Restating obvious syntax.
  • Using comments instead of descriptive names.
  • Writing long paragraphs beside simple code.
  • Leaving outdated explanations after behavior changes.
  • Keeping large blocks of commented-out code.
  • Using triple-quoted strings as block comments.
  • Adding TODO notes with no actionable context.
  • Exposing credentials, customer data, or internal security details.
  • Documenting a bug instead of fixing or testing it.

Practical Refactoring Example

Before:

# Get all users.
u = load_users()

# Remove users that are not active.
u = [x for x in u if x["active"]]

# Sort users by name.
u = sorted(u, key=lambda x: x["name"])

After:

users = load_users()
active_users = [user for user in users if user["active"]]
active_users_by_name = sorted(
    active_users,
    key=lambda user: user["name"],
)

The improved names make the narration unnecessary. Add a comment only if a non-obvious business rule affects filtering or sorting.

A Comment Review Checklist

  • Does the comment explain why or a non-obvious constraint?
  • Can a clearer name or smaller function remove the need?
  • Is the explanation still accurate?
  • Does it reveal sensitive information?
  • Would a docstring, test, issue, or log be a better location?
  • Is a TODO specific and actionable?
  • Is the comment close to the code it describes?

Frequently Asked Questions

How do I write a comment in Python?

Start the comment with #. Python ignores the rest of that line.

Does Python have block comments?

No dedicated block-comment syntax exists. Use consecutive lines beginning with #.

Are triple quotes comments?

No. They create string literals and may create docstrings when placed first in a module, class, or function.

Should every line have a comment?

No. Clear code should explain ordinary operations. Comment decisions, constraints, workarounds, and non-obvious behavior.

Can comments affect program performance?

Ordinary comments are ignored by Python's tokenizer and do not execute as program logic.

Conclusion

Python comments are most valuable when they preserve reasoning that the code cannot express. Use them for constraints, unusual business rules, workarounds, units, security decisions, and performance choices.

Prefer descriptive names, small functions, docstrings for public interfaces, tests for expected behavior, and logs for runtime events. A short accurate comment is better than a long explanation that will quickly become outdated.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Pessoa programando em um notebook, vista de trás, com código desfocado exibido na tela em um fundo escuro
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python Docstrings: Document Code Clearly

    Learn Python docstrings for functions, classes, methods, modules, parameters, returns, exceptions, examples, pydoc, conventions, and documentation tools.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Logo do Python com o texto 'PEP 8' sobre fundo azul escuro, representando o guia de estilo da linguagem
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    PEP 8 in Python: Write Cleaner Code

    Learn PEP 8 in Python with naming, indentation, line length, imports, whitespace, comments, functions, classes, tools, exceptions, and practical refactoring.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    Configuração de logs em aplicações Python usando logging
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python Logging: A Complete Beginner’s Guide

    Learn Python logging from scratch: levels, files, formatters, exceptions, handlers, rotation, and practical examples for reliable applications.

    Ler mais

    Tempo de leitura: 10 minutos
    10/07/2026
    Dicas para otimizar scripts Python lentos
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Why Is Your Python Script Slow? Fixes

    Learn why Python scripts run slowly and how to fix it: use built-ins, list comprehensions, sets, generators, NumPy, cProfile profiling,

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026
    Problemas de travamento com threading em scripts Python
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Python Threading: Stop Your Script From Freezing

    Learn Python threading: why scripts freeze, create and start threads, use join(), avoid race conditions with Lock, and use ThreadPoolExecutor

    Ler mais

    Tempo de leitura: 4 minutos
    03/06/2026
    Criação de cliente TCP simples usando Python
    Best Practices
    Foto de perfil de Leandro Hirt da Academify

    Build a Simple Python TCP Client

    Build a simple Python TCP client using the socket module: connect to a server, send and receive bytes, handle errors,

    Ler mais

    Tempo de leitura: 3 minutos
    03/06/2026