10. Docstrings
A docstring is a string literal placed as the first statement inside a function. It documents what the function does. Triple quotes """ are used so it can span several lines:
- The docstring is not printed and does not change the result.
help(add)shows it, andadd.__doc__returns its text.- It should describe what the function does, not how it does it.
- Every function can have one; it is the standard way to document Python code.
Comment or docstring?
A # comment above a function is only for whoever reads the source file. Python discards it; it is not stored anywhere:
- A comment is not attached to the function:
add.__doc__would beNonewithout the docstring. - A docstring lives inside the function object, so tools can read it:
help(), IDE hovers, Sphinx orinspect.getdoc. - The docstring must be the first statement. A string anywhere else is just an expression that does nothing.
- Rule of thumb: comments explain why; docstrings explain what the function does and how to call it.
The standard: PEP 257
PEP 257 is the official convention for docstrings:
- Start with a one-line summary in the imperative mood:
"""Return the sum of a and b.""", not"""Returns...""". - End the summary with a period.
- Leave a blank line before any extended description.
- In a multi-line docstring, put the closing
"""on its own line. - Do not leave a blank line before the docstring.
- Put types in the signature (
def add(a: int, b: int) -> int); the docstring explains meaning, not types.
For longer functions, the common styles add sections such as Args, Returns and Raises. PEP 257 does not mandate one; Google style is the most readable:
Coming from JavaScript? A docstring is not a comment: it is stored on the function as fn.__doc__ and shown by help(). It plays the role of JSDoc, but it lives in the code and is available at runtime.
Document a function
Define add(a, b) that returns a + b. Its first statement must be the docstring """Return the sum of a and b.""". Print add(2, 3).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Document a function that prints
Define greet(name) with the docstring """Print a greeting for name.""". The body prints Hello, <name>! using an f-string. Call greet("Ada").
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Write a multi-line docstring
Define area(width, height) that returns width * height. Give it a multi-line docstring that follows PEP 257:
- First line: a one-line summary ending in a period.
- Then a blank line and a longer explanation.
- Put the closing
"""on its own line.
Print area(3, 4).
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read the docstring
Define square(n) that returns n * n. Its docstring must be exactly Return n squared.. Print square.__doc__.
Print exactly:
Create a free account to save your progress and unlock chapter 2.