The Art of Commenting in Python
Comments are notes written in your code that are completely ignored by the Python interpreter. Their sole purpose is to be read by humans. Writing good comments is a fundamental skill that separates amateur programmers from professionals. It’s the practice of explaining the why behind your code, not just the what.
Why Bother Commenting?
Clean, readable code is a priority, but even the clearest code can’t explain the original intent or the reasons behind a specific implementation choice.
- Clarity and Context: Comments explain the purpose of complex logic, business rules, or mathematical formulas. They answer the question, “Why was this code written this way?”
- Collaboration: When working in a team, comments are essential for helping your colleagues understand your thought process.
- Future-Proofing: The most important person who will benefit from your comments is your future self. Six months from now, you’ll be grateful for the notes you left behind.
- Debugging: Comments can be used to temporarily disable lines or blocks of code, a common and useful debugging technique.
How to Write Comments in Python
Python provides two primary ways to write comments, plus a special syntax for documentation.
Single-Line Comments (#)
This is the most common type of comment. It starts with a hash symbol (#) and extends to the end of the physical line.
Pyground
Use single-line comments to explain variable assignments and a calculation.
Expected Output:
The interest for one year is: $500.0
Output:
Docstrings: The Official Way to Document Code
A docstring is a special kind of comment that documents what a module, class, function, or method does. It’s placed as the very first statement within the object’s definition and is enclosed in triple quotes ("""...""").
Unlike regular comments, docstrings are not ignored. They become a special __doc__ attribute of the object and are used by tools like help(), IDEs, and documentation generators.
Docstring Example and Usage
Pyground
Define a function with a docstring and then access it using `help()` and the `__doc__` attribute.
Expected Output:
--- Accessing __doc__ --- Calculates the area of a circle from its radius. This function takes a single numerical argument for the radius and returns the calculated area. It handles invalid input. --- Output of help(circle_area) --- Help on function circle_area in module __main__: circle_area(radius) Calculates the area of a circle from its radius. This function takes a single numerical argument for the radius and returns the calculated area. It handles invalid input.
Output:
Common Docstring Formats
For more complex functions, it’s standard practice to use a structured format for your docstrings. This makes them easily parsable by documentation generators like Sphinx.
Google style is highly readable and widely used.
def my_function(arg1, arg2):
"""This is a short summary of the function.
This is a more detailed description that can span
multiple lines.
Args:
arg1 (int): Description of the first argument.
arg2 (str): Description of the second argument.
Returns:
bool: Description of the return value.
"""
return TrueYou don’t need to memorize these formats. The key is to be consistent within your project. Many IDEs and extensions can help you generate these docstrings automatically.
Best Practices for Effective Commenting
-
Keep Comments Up-to-Date: A comment that is wrong is worse than no comment at all. If you change the code, change the comment.
-
Comment the “Why,” Not the “What”: Your code should be readable enough to explain what it’s doing. The comment should explain why.
🚫Bad:
x = x + 1 # Add one to x(This is obvious from the code.)✅Good:
x = x + 1 # Increment to account for the zero-based index.(This explains the reason.) -
Write Comments as You Code: Don’t wait until the end to add comments. You’ll forget the nuances of your own logic.
-
Use Comments for Planning: Use
TODOorFIXMEcomments to leave notes for yourself or others about future work.# TODO: Refactor this to use a more efficient algorithm. # FIXME: This fails when the input is negative. -
Strive for Self-Documenting Code: The best comment is often a well-named variable or function.
🚫Bad:
d = 5 # d is the number of days✅Good:
days_since_last_login = 5(The name itself is the comment.)