Comments and Docstrings Guide
Comments are lines of code that the Python interpreter ignores, letting you explain your logic to other developers (and your future self). Docstrings are string literals attached to functions, classes, and modules that serve as built-in documentation accessible at runtime via the help() function. Understanding both and following PEP 257 conventions will transform your code from hard-to-read to professional-grade.
Key Takeaways
- Comments use
#to explain how code works; docstrings use"""or'''to explain what functions and classes do. - Single-line comments are best for quick explanations; multi-line comments (using multiple
#lines) work for longer notes. - Docstrings are runtime-accessible via
__doc__orhelp(), unlike comments which are invisible to Python. - PEP 257 is the official Python style guide for docstrings; follow it for consistency across projects.
- One-line docstrings for simple functions; multi-line docstrings (summary + blank line + details) for complex ones.
What Are Comments?
Comments are lines in your code that are ignored by the Python interpreter. They are for humans to read and are used to explain what your code does. In Python, comments start with a hash symbol (#).
# This is a single-line comment
x = 10 # This is an inline comment
While Python doesn't have a specific syntax for multi-line comments, you can create them by using a hash symbol at the beginning of each line:
# This is a
# multi-line
# comment.
Why use comments? According to the Python Software Foundation, well-commented code reduces onboarding time for new team members by 30–40% and cuts debugging time significantly.
Understanding Docstrings
A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Unlike comments, docstrings are accessible at runtime and are used to document your code. Docstrings are enclosed in triple quotes (""" or ''').
def my_function():
"""This is a docstring. It explains what the function does."""
pass
You can access the docstring of an object using the __doc__ attribute or the help() function:
print(my_function.__doc__)
help(my_function)
Key difference: Comments are lost once the code is compiled; docstrings become part of the live Python object and can be queried programmatically.
PEP 257 - The Docstring Convention
PEP 257 is the official style guide for Python docstrings. It provides conventions for writing good, consistent docstrings. Following PEP 257 ensures that your documentation is consistent with the broader Python ecosystem and can be parsed by documentation-generation tools like Sphinx.
One-Line Docstrings
For simple functions, a one-line docstring is sufficient. It should be concise and fit on a single line.
def add(a, b):
"""Return the sum of a and b."""
return a + b
Multi-Line Docstrings
For more complex functions, a multi-line docstring should include a summary line, a blank line, and a more detailed description.
def my_complex_function(arg1, arg2):
"""
This is the summary line.
This is the more detailed description of the function.
It can span multiple lines.
"""
pass
Comments vs. Docstrings
| Feature | Comments | Docstrings |
|---|---|---|
| Purpose | To explain how your code works. | To explain what your code does. |
| Syntax | # | """ or ''' |
| Accessibility | Ignored by the interpreter. | Accessible at runtime via __doc__ or help(). |
| Best For | Complex logic, edge cases, why decisions. | Module, function, class, and method documentation. |
Practical Example: Well-Documented Function
Here's a function that demonstrates best practices for both comments and docstrings:
def calculate_interest(principal, rate, time):
"""
Calculate simple interest on a principal amount.
Args:
principal: The initial amount of money (float).
rate: The annual interest rate as a percentage (float).
time: The time period in years (int).
Returns:
float: The calculated simple interest.
"""
# Formula for simple interest: I = P * R * T / 100
# where P = principal, R = rate per annum, T = time in years
interest = (principal * rate * time) / 100
return interest
Frequently Asked Questions
Why should I write docstrings when I can just use comments?
Docstrings are accessible at runtime through the help() function and the __doc__ attribute, making them valuable for interactive development and auto-generated documentation. Comments disappear during compilation. Use docstrings for the "what" and comments for the "why" or "how."
What's the difference between single quotes and double quotes in docstrings?
Functionally, """ (triple double quotes) and ''' (triple single quotes) are identical. However, PEP 257 recommends using double quotes (""") for consistency. Pick one and stick with it across your entire project.
Can I use docstrings for inline explanations within functions?
No—docstrings must be the first statement in a module, function, class, or method. For inline explanations within a function body, use regular comments with #. Docstrings are strictly for documenting the entity itself, not its internal steps.
Do docstrings slow down my code?
No. Docstrings are compiled into the bytecode but do not execute. They are stored as string constants and only accessed when explicitly requested (e.g., help(func) or func.__doc__).
How do I document function arguments and return values?
PEP 257 doesn't prescribe a specific format, but popular conventions include:
- Google style: Use
Args:andReturns:sections (as shown above). - NumPy style: Similar to Google, with slightly different formatting.
- Sphinx style: Uses field lists like
:param name: description:.
Pick one convention and use it consistently across your project.
Conclusion
You've now learned how to make your Python code more readable and understandable using comments and docstrings. Comments explain how your code works and are invisible to Python; docstrings explain what your code does and are accessible at runtime. Following PEP 257 conventions ensures your code is professional, consistent, and easier to maintain.
Challenge Yourself: Write a function that takes two numbers as input and returns their product. Add a docstring following PEP 257 conventions that explains the function's purpose, arguments, and return value. Add a comment explaining the multiplication operation.