How do you write multi-line comments and docstrings in Python? | A1Lab@MZeeshanM to PythonEnglish • 6 days ago

How do you write multi-line comments and docstrings in Python?

message-square
0

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 (raising IndentationError if misaligned), and still triggers SyntaxWarning on invalid backslash escape sequences (e.g., """C:\new\path"""). Use # for commenting out blocks of code—most IDEs toggle # across selected lines automatically with Ctrl+/ (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, or def / async def block. Placing # comments above it is fine, but placing any executable statement or assignment before it turns the string into an ordinary dead expression (obj.__doc__ remains None).
  • 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 prevent SyntaxWarning: invalid escape sequence.
    • Keep a blank line after the summary line in multi-line docstrings, and indent the closing """ to match the opening 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 / Returns headers) — standard across scientific Python (NumPy, SciPy, Pandas).
    • reStructuredText / Sphinx style (:param x:, :type x:, :return:) — traditional Sphinx documentation format.

Comparison of Multi-Line Comments vs. Docstrings

Feature Multi-Line Block Comment (# ...) Docstring ("""...""") Unassigned Triple-Quoted String ("""...""")
Syntax # Line 1 followed by # Line 2 """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 (# C:\new 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.