Python Docstrings: Documenting Functions
A docstring is a string on the first line of a function body that says what the function does.
Here you write docstrings and read them back with __doc__ and help().
Read Defining Functions first. Every example runs on
its own: press Run.
Write a docstring
Put a string in triple quotes (""") as the first statement inside the
function. Triple quotes let the string run over several lines.
Python saves that string on the function in a special attribute called
__doc__ (two underscores on each side). Read it with a dot: show_greeting.__doc__.
def show_greeting():
"""Print a short welcome message."""
print("Hello!")
show_greeting()
print(show_greeting.__doc__)
The call prints Hello!. The docstring does not run as code; __doc__ gives it back.
Read it with help()
help() prints the function's name, its parentheses and its docstring.
Editors show the same text when you hover over a call.
def show_menu():
"""Print the three menu choices."""
print("1: Play")
print("2: Scores")
print("3: Quit")
help(show_menu)
It prints Help on function show_menu in module __main__:, then
show_menu() and the docstring, indented. The menu itself is not printed:
help() reads the function without calling it.
Docstring or comment?
A docstring tells someone using the function what it does. A # comment
explains how a line works to someone reading the code. Only the docstring
is kept on the function.
def show_rules():
# one print per rule keeps them easy to edit
print("Roll the dice.")
print(show_rules.__doc__)
This prints None: the function has no docstring, because a comment is not
a string and Python throws it away.
Longer docstrings
For a bigger function, write a one-line summary, a blank line, then details. The first line should still make sense on its own.
def show_board():
"""Print an empty three-by-three board.
Each row is three dots. The board is not stored anywhere.
"""
print("...")
print("...")
print("...")
print(show_board.__doc__.splitlines()[0])
It prints Print an empty three-by-three board.. splitlines() splits the
docstring into a list of lines, and [0] takes the first: the summary line,
which is what most tools list.
Note: Style guides such as PEP 257 add sections for parameters and return values. This lesson leaves those out; see Parameters & Return for what they describe.
See also: Decomposition.
Your turn
Add a docstring to show_score() that reads Print the current score., then
print the docstring and call the function.
def show_score():
# add the docstring here
print("Score: 0")
# print show_score's docstring, then call show_score()
Expected output
Print the current score.
Score: 0