Prefix each line with (the official PEP 8 standard for multi-line block comments), and use triple-quoted string literals ("""...""") placed as the very first statement inside a module, class, function, or method to write docstrings (which Python attaches to the object’s __doc__ attribute at runtime).
Basic Example
# 1. Multi-line block comment (PEP 8 standard):
# Use consecutive '#' characters at the same indentation level.
# Python ignores these lines completely during bytecode compilation.
def calculate_area(width: float, height: float) -> float:
"""Calculate the area of a rectangle.
Args:
width: The horizontal dimension in meters.
height: The vertical dimension in meters.
Returns:
The computed area in square meters.
"""
return width * height
# 2. Accessing the docstring programmatically at runtime
print(calculate_area.__doc__)
Key Details & Edge Cases
- Why unassigned triple-quoted strings (
"""...""") are NOT true comments: Python has no dedicated block-comment delimiter like C/Java’s/* ... */. While an unassigned"""..."""literal placed mid-function is discarded by the compiler if unused, it is still parsed as a string literal node in the Abstract Syntax Tree (AST), must obey Python’s indentation rules (raisingIndentationErrorif misaligned), and still triggersSyntaxWarningon invalid backslash escape sequences (e.g.,"""C:\new\path"""). Usefor commenting out blocks of code—most IDEs toggleacross selected lines automatically withCtrl+/(Cmd+/on macOS). - Docstring placement matters (
__doc__): A triple-quoted string becomes a docstring only when it is the very first statement in a module, class, ordef/async defblock. Placingcomments above it is fine, but placing any executable statement or assignment before it turns the string into an ordinary dead expression (obj.__doc__remainsNone). - PEP 257 docstring conventions:
- Always use triple double-quotes (
"""..."""), even for single-line docstrings ("""Return the user's full name."""), so expanding them later requires no quote changes. - Use raw triple quotes (
r"""...""") whenever a docstring contains backslashes (such as regular expressions, Windows paths, or LaTeX math) to preventSyntaxWarning: invalid escape sequence. - Keep a blank line after the summary line in multi-line docstrings, and indent the closing
"""to match the opening quotes.
- Always use triple double-quotes (
- Common docstring formatting styles:
- Google style (compact
Args:,Returns:,Raises:sections) — popular in application code and supported by Sphinx (napoleon) and MkDocs. - NumPy style (underlined
Parameters/Returnsheaders) — standard across scientific Python (NumPy,SciPy,Pandas). - reStructuredText / Sphinx style (
:param x:,:type x:,:return:) — traditional Sphinx documentation format.
- Google style (compact
Comparison of Multi-Line Comments vs. Docstrings
| Feature | Multi-Line Block Comment () |
Docstring ("""...""") |
Unassigned Triple-Quoted String ("""...""") |
|---|---|---|---|
| Syntax | followed by |
"""Summary...""" as first statement |
"""Text...""" anywhere else in code |
Stored in __doc__ at runtime? |
No (stripped by lexer) | Yes (obj.__doc__ and help(obj)) |
No (__doc__ stays None) |
| Parsed for escape sequences? | No ( is completely ignored) |
Yes (use r"""...""" for backslashes) |
Yes (can emit SyntaxWarning on \n, \t, \U) |
| Must match block indentation? | Recommended by PEP 8 (not enforced) | Yes (IndentationError if misaligned) |
Yes (IndentationError if misaligned) |
| Best Used When | Explaining complex implementation logic or temporarily disabling code. | Documenting public modules, classes, functions, and methods. | Never as a comment—use instead. |
You must log in or register to comment.
