A docstring is the string literal that comes first in a module, a class, or a function, and it is the one piece of documentation that travels with the code everywhere it goes. When it is written well, it tells a colleague what a function does, what it expects, and what it hands back, and they never have to open the source at all.
The previous lesson in this module covered "Type Hints: Annotations That Pay Off", and this lesson is the last one in the Python Modules and Packages module.
What is a docstring, and when does Python read it?
If the first statement in the body of a module, a class, or a function is a string literal, then Python stores it as that object's __doc__ attribute. That is the whole mechanism. There is no special syntax, no decorator, and no import to remember. Because the literal is never treated as code, it costs nothing at runtime beyond a few bytes of memory.
def celsius_to_fahrenheit(celsius):
"""Convert a Celsius temperature to Fahrenheit.
Args:
celsius: Temperature in degrees Celsius.
Returns:
The equivalent temperature in degrees Fahrenheit.
"""
return celsius * 9 / 5 + 32
print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit.__doc__.splitlines()[0])
The one-line summary at the top is the part that matters most, because it is what appears in help() listings, in the tooltips of your editor, and in generated reference documentation. Write it as a full sentence that starts with a verb, such as "Convert" and not "Converts" or "A function that converts", and end it with a full stop. Readers scan that first line far more often than they read the rest of the body.
What belongs in a docstring, and what does not?
A useful docstring answers four questions, always in this order. What does the thing do? What does it need? What does it return? And what might it raise? Everything else belongs somewhere else.
class ShoppingCart:
"""A cart that holds products and their quantities.
Attributes:
items: Mapping of product name to quantity in the cart.
"""
def __init__(self):
"""Create an empty cart."""
self.items = {}
def add(self, product, qty=1):
"""Add qty of a product to the cart.
Args:
product: Name of the product to add.
qty: How many to add. Must be positive.
Raises:
ValueError: If qty is not positive.
"""
if qty <= 0:
raise ValueError('qty must be positive')
self.items[product] = self.items.get(product, 0) + qty
cart = ShoppingCart()
cart.add('mug', 2)
print(cart.items)
print(ShoppingCart.__doc__.splitlines()[0])
print(ShoppingCart.add.__doc__.splitlines()[0])
Notice what is missing. The docstring does not repeat the signature, it does not narrate the assignment line by line, and it does not apologise for anything. It also does not go out of date quietly, because when a parameter is renamed the type checker flags the mismatch, and the docstring is the thing that you remember to update in the same breath.
Two habits are worth adopting early. Document the Raises section, because the exception type is the part of an interface that people cannot guess on their own. And keep one-line docstrings genuinely on one line, because a multi-line docstring on a trivial function is a signal that the function does more than its name suggests.
Which docstring style should you use?
Three conventions dominate, and every documentation generator accepts all three of them. Pick one for the project and stay with it, because mixed styles are worse than any single style.
| Style | Sections look like | Best for |
|---|---|---|
| Google style | Args:, Returns:, Raises: | General projects. It is the most widely recognised and the easiest to read in plain text. |
| NumPy style | Parameters and Returns with indented type blocks | Scientific and numerical libraries where the parameter list is long and typed. |
| reStructuredText | :param x: and :returns: | Projects that are already documented with Sphinx, and older codebases. |
A short function does not need any of them. The sentence "Return the total price including tax." is a complete docstring for a two-line function, and adding an empty Args: section to it is only noise.
Readable code and good docstrings are the same investment seen from two sides. A docstring forces you to state the contract before you write the body, and a contract that you cannot state in two lines is usually a contract that you have not really thought about yet. Names follow the same logic. cart_total tells a reader much more than calc does, and no amount of documentation rescues a name that hides its own meaning.
When should you write a comment instead?
The rule of thumb is short. A docstring describes what a thing is and what it does, while a comment explains something that a reader of that code could not work out on their own. A comment that simply restates the code is worse than no comment at all, because it adds something to maintain and it teaches nobody anything.
subtotal = 19.99
discount = 2.00
# BAD - the comment says what the next line already says.
# add the discount to the total
total = subtotal + discount
print(total)
items = list(range(150))
# GOOD - the comment explains a rule that the code cannot show.
# The payments API rejects batches larger than 100 items.
batch = min(len(items), 100)
print(batch)
Comments should also explain decisions and not mechanics. Why is the retry limit three? Why does the cache expire after thirty seconds? Why is an unusual spelling kept for compatibility with an external system? If the reason is not in the code and not in the docstring, then it disappears the moment that the code changes, and the next person is left to guess.
How do you read docstrings without leaving the terminal?
Three tools cover almost every case. help() prints the full documentation for an object, inspect.getdoc() returns it as a string, and python -m pydoc generates browsable documentation for a whole module.
import inspect
class Base:
"""Base class for the account hierarchy."""
class Savings(Base):
pass
class Premium(Savings):
"""An account that earns interest."""
def greet(name, excited=False):
"""Return a greeting for name."""
if excited:
return 'Hi ' + name + '!'
return 'Hi ' + name
print(inspect.getdoc(Savings))
print(Savings.__doc__)
print(inspect.signature(greet))
print(greet.__doc__)
That first line of output is the one to notice. inspect.getdoc(Savings) returns "Base class for the account hierarchy.", while Savings.__doc__ is None. The getdoc function looks up the class hierarchy for an inherited docstring, which is why it is the better choice when you are reading documentation in your own code. Use it whenever you cannot be sure that the object has a docstring of its own.
# Browse the documentation of a module in the terminal.
python -m pydoc mymodule
# The same thing, but with the source shown as well.
python -m pydoc -s mymodule
Next steps
- Every module, class, and public function gets a docstring with a one-line summary that starts with a verb.
- Document the parameters, the return value, and the exceptions that you raise, because those are the parts that a caller has to get right.
- Choose one section style per project and then apply it consistently.
- Keep comments for reasoning and for constraints, and never for narration.
- Read your own docstring through
help()once a month. If it reads oddly, then the function probably wants a new name.
Try it yourself: Pick the longest function in one of your own scripts. Delete its comments and its docstring, and then write them again from the point of view of the caller. What goes in, what comes out, and what can go wrong. Time yourself as you do it. If the rewrite took more than two minutes, that is a sign that the interface of the function is doing too much, and splitting it into two smaller functions usually makes the documentation easy to write.