๐ฆ Python Fundamentals
Module 2 ยท Topic 5
Comments & Docstrings
Write meaningful comments and professional docstrings that make your code maintainable and self-documenting.
Theory
Comments in Python:
Single-line Comments: Start with #
# This is a comment
x = 10 # Inline comment
Multi-line Comments: Use consecutive # lines (no block comment syntax)
# This is a
# multi-line comment
# spanning three lines
Docstrings โ The Professional Way:
Docstrings are string literals that appear as the first statement in a module, class, or function. They become the __doc__ attribute.
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.
Raises:
ValueError: If radius is negative.
"""
if radius < 0:
raise ValueError("Radius cannot be negative")
return 3.14159 * radius ** 2
Popular Docstring Styles:
- Google style โ Args:, Returns:, Raises: sections
- NumPy style โ Uses underlined section headers
- reStructuredText โ :param name: description (used by Sphinx)
When to Comment:
- Explain WHY, not WHAT (the code shows what)
- Document complex algorithms or business logic
- Mark TODOs:
# TODO: optimize this query - Explain workarounds:
# Workaround for bug #123
Syntax
# Single-line comment
"""
Docstring for module/class/function
"""
def func():
"""One-line docstring."""
pass
def func2(param):
"""Summary line.
Args:
param: Description.
Returns:
Description of return value.
"""
pass