Sub topic 14
Documenting a function with a docstring
This chapter assumes you can define functions with def, use parameters and return, and read type hints. Here you will add documentation that Python stores with the function and that tools can read.
What a docstring is
A docstring is a string literal placed as the first statement in a function body. Python saves it in the function's __doc__ attribute. A # comment is discarded when the code is compiled, so only a docstring can be read at run time.
def average(values: list[float]) -> float:
"""Return the arithmetic mean of values.
Raises ValueError if values is empty.
"""
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)
print(average.__doc__)
help(average)help(average) prints the signature followed by the docstring. Editors show the same text when you hover over a call.
Writing a useful docstring
Start with a one-line summary. Write it as a command, such as "Return the mean", and end it with a period. If more detail is needed, leave a blank line and then add paragraphs.
Describe what the signature cannot say:
- What each parameter means, including units or allowed ranges.
- What the function returns, and when it returns something unexpected.
- Which exceptions it raises, and why.
- Side effects, such as modifying an argument or writing a file.
For longer docstrings, pick one section style and use it everywhere in the project. This example uses the Google style:
def clamp(value, low=0, high=100):
"""Limit value to the range from low to high.
Args:
value: The number to limit.
low: Smallest allowed result.
high: Largest allowed result.
Returns:
low if value is below low, high if value is above high,
otherwise value.
"""
return max(low, min(value, high))
print(clamp.__doc__.splitlines()[0]) # Limit value to the range from low to high.NumPy style and reStructuredText style are the other common formats. They carry the same information in a different layout.
Docstrings and type hints
Type hints already record the types, so the docstring does not need to repeat them. Use the docstring for meaning. In average, the hint says list[float], and the docstring says that an empty list raises ValueError.
Common errors
- Using a comment instead of a docstring.
# Return the meanabove or inside the function is invisible tohelp(). - Putting the string in the wrong place. The docstring must be the first statement. If any code comes before it, the string is just an unused expression and
__doc__isNone. - Letting the docstring go stale. After you change a parameter or an exception, update the text too. A wrong docstring is worse than none.
- Restating the code. "Loops over values and adds them" repeats the body. Say what the function promises instead.
- Using single quotes for multi-line text. Use triple double quotes,
""", as the convention requires.
Exercise
Exercise
A function starts with the line # Return the total price and then has its code. What does help() show for the description, and how do you fix it?
Show answer
help() shows no description, because a comment is not stored on the function. Replace the comment with a docstring as the first statement in the body, for example """Return the total price.""". Python then saves it in __doc__.