Python Comments & Docstrings
In Python, comments are notes written in code for human readers, ignored by the Python interpreter during execution. Docstrings (documentation strings) are functional documentation strings that remain attached to modules, classes, functions, or methods at runtime and can be inspected dynamically.
Python Comments
Python provides single-line and multi-line commenting patterns. Comments begin with the hash symbol (#).
Single-Line Comments
Single-line comments start with # and extend to the end of the line.
# Calculate the area of a circle
radius = 5.0
area = 3.14159 * (radius ** 2) # Inline comment explaining radius squared
Multi-Line Comments
Python does not have a distinct syntax for multi-line block comments like /* ... */ in C or Java. Instead, you can use consecutive single-line comments or unassigned multiline strings.
Standard Block Comments (Recommended by PEP 8)
Place consecutive # symbols at the start of each line:
# The following block performs a standard data transformation:
# 1. Strip leading/trailing whitespaces.
# 2. Convert all characters to lowercase.
# 3. Replace internal spaces with hyphens.
cleaned_text = text.strip().lower().replace(" ", "-")
Unassigned Multiline String Literals
Triple-quoted strings (''' or """) not assigned to a variable or placed as a docstring are ignored by Python during execution, functioning as multi-line comments:
"""
This is an unassigned multiline string literal.
It is evaluated by Python but immediately discarded,
making it a common pattern for quick temporary comments.
"""
print("Execution continues normally.")
Python Docstrings
A docstring is a string literal that occurs as the very first statement in a module, function, class, or method definition. Unlike regular comments, docstrings are parsed into the __doc__ attribute of the object.
Accessing Docstrings
Docstrings can be accessed programmatically or viewed using Python's built-in help() function:
def add_numbers(a: int, b: int) -> int:
"""Return the sum of two integers."""
return a + b
# Programmatic access
print(add_numbers.__doc__)
# Output: Return the sum of two integers.
# Interactive help view
help(add_numbers)
Types of Docstrings
Single-Line Docstrings
Used for simple functions, methods, or classes. The entire docstring fits on one line, with opening and closing triple quotes on the same line.
def square(n: float) -> float:
"""Return the square of a given number."""
return n * n
Multi-Line Docstrings
Used to describe complex parameters, return values, exceptions, and usage examples. They consist of a summary line, followed by a blank line, followed by elaborated details.
def divide(dividend: float, divisor: float) -> float:
"""
Perform floating-point division between two numbers.
Parameters:
dividend (float): The number to be divided.
divisor (float): The number by which to divide.
Returns:
float: The result of the division.
Raises:
ZeroDivisionError: If the divisor is equal to zero.
"""
if divisor == 0:
raise ZeroDivisionError("divisor cannot be zero.")
return dividend / divisor
Comments vs. Docstrings Summary
| Feature | Comments (#) |
Docstrings ("""...""") |
|---|---|---|
| Primary Purpose | Explain why code works a certain way (for developers). | Explain what the module, class, or function does and how to use it. |
| Location | Anywhere within the code. | First line inside a module, class, function, or method. |
| Runtime Persistence | Stripped out at compilation; not available at runtime. | Retained at runtime; accessible via __doc__ or help(). |
| Tooling Support | Used by linter rules (e.g., # noqa). |
Used by auto-documentation generators (Sphinx, Pydoc). |