Write Useful Python Function Docstrings
Core idea
A docstring is a string literal placed as the first statement of a function body. It documents what the function does. Use triple quotes for multiline text, and describe the input assumptions and returned value when they are not obvious. Python exposes it through function.__doc__, an attribute containing the documentation string or None.
def minutes(hours): """Return the number of minutes for the given hours.""" return hours * 60
print(minutes(2))print(minutes.__doc__)The function result and documentation are separate values.
Describe a constraint
def per_box(total, boxes): """Return items per box.
boxes must be a positive integer. """ return total / boxes
print(per_box(12, 3))print("positive integer" in per_box.__doc__)The docstring tells callers what boxes must satisfy; it does not enforce the constraint.
A comment is not a docstring
def count(): # Return a fixed count. return 3
print(count.__doc__)A comment does not set the function documentation attribute.
Common mistake
A docstring is not runtime validation. A string after an executable statement is not the function docstring. Keep the text accurate when changing a function.
Practice
Write a docstring for a function that calculates the cost of a nonnegative item count at a fixed price. Include the input assumption and result, then inspect doc.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Function documentation
Check your understanding of docstrings.
What is printed?
def count(): """Return a count.""" return 3print(count.__doc__)What is printed?
def count(): # Return three. return 3print(count.__doc__)What is printed?
def double(n): """Return double a nonnegative integer.""" return n * 2print(double(-1))What should a useful docstring describe?