How do I write and use comments and docstrings in Python?
· Category: Python Programming
Short answer
Use # for single-line comments and triple-quoted strings (""") for multi-line comments and docstrings. Docstrings document modules, classes, and functions and are accessible at runtime via __doc__.
Steps
- Add inline comments with
#to explain non-obvious logic. - Write a docstring immediately after the
deforclassline. - Follow PEP 257 conventions for docstring formatting.
# This is a single-line comment
def calculate_area(radius):
"""Calculate the area of a circle given its radius.
Args:
radius (float): The radius of the circle.
Returns:
float: The area of the circle.
"""
import math
return math.pi * radius ** 2
print(calculate_area.__doc__)
Tips
- Comments should explain why, not what; the code should be self-explanatory for the latter.
- Use docstring styles consistently: Google style, NumPy/SciPy style, or reStructuredText.
- Tools like Sphinx and pydoc can generate documentation from docstrings.
Common issues
- Misplacing a docstring after any statement inside a function makes it a regular string, not a docstring.
- Over-commenting obvious code adds noise; under-commenting complex algorithms creates confusion.
- Block comments without
#on every line are not valid Python syntax unless they are string literals.