Docstrings
A docstring is the triple-quoted string at the start of a function that explains what it does, and Python stores it in `__doc__`.
Used in 107 lessons of the course, from 00.01.
A docstring is a string placed as the first statement inside a function, class or module. By convention it uses triple quotes (""").
It is not a comment. Python stores it in the object's __doc__ attribute, so other tools (help(), your editor, frameworks) can read it.
The convention is to start with a short line saying what the function does, in the imperative: "Print the definition of term...". If you need more detail, leave a blank line and keep going.
Why it matters: the code says how, the docstring says what and why. In the course you will see docstrings on almost every function, like the one in lesson 00.01 that explains what it does with term.
def f():
"""Say hi."""
If the string is not the first statement, it stops being a docstring.
Reach for it when: you write a function, class or module that someone else (or you in a month) will use and you want to explain what it does.
Examples
Common mistake
def add(a, b):
x = a + b
"""Add two numbers."""
return x
print(add.__doc__)Why: The string is not the first statement in the body, so Python does not store it as a docstring.
How to write it: Put the string right after the def line, before any other statement.
