Python Comments
Types of Comments
Comments document intent and are ignored by the Python interpreter’s execution. Python has true single-line comments and uses string literals as documentation (docstrings). There is no dedicated multi-line comment syntax.
- **Single-line**: Starts with `#` and continues to the end of the line
- **Docstrings**: Triple-quoted strings placed as the first statement in a module, class, or function; used for documentation and tooling (not general comments)
- **Block comments**: Consecutive lines starting with `#` to explain larger sections of code
Comment Examples
Example
# Module docstring (visible to help())
"""Utilities for math operations."""
# Single-line comment
# Explain *why* a decision was made, not just what the next line does.
# Block comment (multiple # lines)
# Normalize the input to avoid downstream edge cases
# and ensure consistent behavior across platforms.
def calculate(x, y):
"""Return the sum of x and y.
Args:
x (int | float): First operand.
y (int | float): Second operand.
Returns:
int | float: The result of addition.
"""
result = x + y
return result # Inline comment: result already validated above
Output
# No output - comments and docstrings do not execute
Best Practices
ℹ️ Note: Docstrings can be accessed via `help()` or the `__doc__` attribute and are parsed by tools like Sphinx and IDEs.
Do | Don't |
---|---|
Explain why, not what | Write obvious comments like `x = 5 # set x to 5` |
Keep comments and docstrings up-to-date | Leave outdated or misleading comments |
Use docstrings for public functions/classes/modules | Omit parameter/return info for reusable APIs |
Comment complex or non-obvious logic | Over-comment straightforward code |
Special Comment Cases
Certain comment conventions are recognized by operating systems or developer tools:
⚠️ Warning: Shebang must be on the very first line. Encoding declarations (rarely needed in Python 3) must appear on the first or second line.
Example
#!/usr/bin/env python3 # Shebang for Unix-like systems (must be the first line)
# -*- coding: utf-8 -*- # Encoding declaration; UTF-8 is default in Python 3
# Linting / formatting / type-checking pragmas
value = 1/3 # noqa # Tell linters to ignore a specific warning on this line
from typing import Any
def f(x: Any) -> int:
return x # type: ignore[return-value] # mypy: suppress type error here
# Black formatter control
# fmt: off
very = "spaced" # preserved
# fmt: on
# Task tags (for humans/tools)
# TODO: Add input validation
# FIXME: Handle division by zero