Docstrings document modules, classes, and functions; comments explain local code decisions. They serve different readers and tools.
Understanding the Concept
A docstring is a string literal placed at the beginning of a module, function, or class body. It often uses triple quotation marks for readable multiline content and becomes accessible through the object’s __doc__ attribute and help(). A # comment is ignored by the runtime and is not stored as that object’s documentation. Write a docstring describing what a function does, its important inputs, and its result. Use short comments only when the implementation needs an explanation.
When and Why You Would Use This
A small function shows both conventions. Its docstring explains its interface, while an optional comment could explain an unusual implementation decision. You do not need a comment before every return statement.
Practical Example
def calculate_square(side_length):
"""Return the area of a square from the length of one side."""
return side_length * side_length
print(calculate_square(4))
print(calculate_square.__doc__)
Understanding the Example
The function returns 16. The next print displays the docstring text. Tools can display this documentation because it is associated with the function, unlike an ordinary # comment.
Example Output
16
Return the area of a square from the length of one side.
Try It Yourself
Add a docstring to a greeting function and inspect it using help() or __doc__.
Common Beginner Mistakes
- Placing a docstring after executable statements in the function body.
- Using long docstrings to describe every obvious line of implementation.
- Assuming a comment automatically appears in help() as function documentation.
Key Takeaways
- A docstring documents a module, class, or function interface.
- A comment explains local choices or assumptions.
- help() and __doc__ expose available docstrings.