Python Docstrings
A docstring is a string on the first line inside a function that says what the function does. Python stores the docstring on the function.
A docstring on the first line
The string right after the def line is the docstring. It does not change how the function runs.
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}!"
print(greet("Ada"))Read it with .__doc__
Python stores the docstring on the function itself. You can print it like any string.
def greet(name):
"""Return a greeting for name."""
return f"Hello, {name}!"
print(greet.__doc__)A multi-line docstring
The first line sums the function up. Later lines add the details.
def area(width, height):
"""Return the area of a rectangle.
Both sides are numbers.
The result is width times height."""
return width * height
print(area.__doc__)Ask for help
help() shows the docstring with extra details around it. Try this line in your own Python window.
help(greet)Example
def min_max(numbers):
"""Return the smallest and largest numbers in a list."""
smallest = min(numbers)
largest = max(numbers)
return smallest, largest
scores = [4, 9, 2, 7]
print(min_max(scores))
print(min_max.__doc__)Key points
- Docstring: the string on the first line inside a function.
- It says what the function does.
- .__doc__: the place where Python stores a function's docstring text
- Use help() to show a function's docstring with extra details
- A one-line docstring fits a simple function.
- A multi-line docstring adds detail below the first line.
- Write what the function does and what it returns.
- Skip how the code works inside.
In this example, min_max is the function you met in the return values lesson. Its first line inside is now a docstring. The docstring says what the function does and what it returns. The body still finds the smallest and largest numbers and returns both. The first print shows the result for the scores list. The second print reads the docstring back with .__doc__.
Note
A docstring is not a comment.
Python keeps it, so help() and other tools can show it later.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Where does a docstring go?