1. Comments vs. Docstrings
Compile-Time Stripping vs. Runtime Reflection
- Single-line comments start with a hash symbol (#) and are completely discarded by the Python compiler into bytecode.
- Docstrings are string literals placed immediately as the first statement of a module, function, class, or method.
- CPython retains docstrings as bytecode constants and binds them to the object’s `__doc__` special attribute.
def calculate_bmi(weight_kg, height_m):
"""Calculate Body Mass Index.
Args:
weight_kg: Weight in kilograms (float)
height_m: Height in meters (float)
Returns:
Calculated BMI value (float)
"""
return weight_kg / (height_m ** 2)
print(calculate_bmi.__doc__)
💡 Key Takeaway: Docstrings are introspectable at runtime via obj.__doc__ and help(obj), making them essential for reusable software.