Lesson 9 of 10
A docstring is a string on the first line of a function body. It documents what the function does, and Python keeps it around at runtime.
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area(3, 4))
print(area.__doc__)
Triple quotes are the convention, even for a one-liner, because it leaves room to grow.
Docstrings versus comments
They serve different readers:
- A
#comment explains how the code works, to someone editing it. - A docstring explains what the function does and how to call it, to someone using it.
def area(width, height):
"""Return the area of a rectangle."""
# Multiplication is faster than repeated addition here.
return width * height
Someone calling area() needs the docstring. Only someone modifying the body needs the comment.
A fuller docstring
For anything non-obvious, describe the arguments and the return value:
def divide(a, b):
"""Divide a by b.
Args:
a: The number to divide.
b: The number to divide by. Must not be zero.
Returns:
The result of a / b as a float.
"""
return a / b
print(divide(10, 4))
The first line is a short summary in the imperative — "Return the area", not "Returns the area" or "This function returns...". Then a blank line, then the details.
help()
Python's built-in help() prints the docstring. This is where the payoff shows up — your own
functions get documentation in exactly the same way the standard library does.
def area(width, height):
"""Return the area of a rectangle."""
return width * height
help(area)
What makes a good docstring
Don't restate the code:
def add(a, b):
"""Add a and b."""
return a + b
That earns nothing — the name already said it. Save your words for what isn't obvious: edge cases, units, assumptions, what happens on bad input.
def average(numbers):
"""Return the mean of a list of numbers.
Returns 0 for an empty list rather than raising.
"""
if not numbers:
return 0
return sum(numbers) / len(numbers)
print(average([1, 2, 3]))
print(average([]))
That second line is genuinely useful — a caller could not have guessed it.
Try it yourself
Write a documented average() and call it with a normal list and an empty one.
Checkpoint
- A docstring is a
"""triple-quoted string"""as the first line of the body. - Docstrings say what for callers; comments say how for editors.
- First line: short imperative summary, then blank line, then detail.
- Document the surprising parts, not what the name already tells you.
Questions about this lesson
Log in to ask a question.