Type hints and docstrings
Overview
When you come back to a function after a month — or someone else reads it — two questions come first: what does it do, and what does it take and give back? Docstrings answer the first; type hints answer the second. Both are free to write and pay off quickly.
Docstrings
A docstring is a string literal written as the first statement of a function (or module, or class). By convention it uses triple double quotes:
def average(numbers):
"""Return the arithmetic mean of a non-empty list of numbers."""
return sum(numbers) / len(numbers)Unlike a # comment, Python keeps the docstring and makes it available:
help(average)Help on function average in module __main__:
average(numbers)
Return the arithmetic mean of a non-empty list of numbers.Editors show it when you hover over a call, too.
Writing good docstrings
- First line: one sentence in the imperative mood saying what the function does — “Return…”, “Calculate…”, “Send…” — ending with a full stop.
- For more complex functions, add a blank line, then details: arguments, return value, errors raised, and an example.
def shipping_cost(total, country):
"""Return the shipping cost for an order.
Orders of 100 or more ship free. Domestic (IN) orders cost 5,
everything else 15.
Raises ValueError if total is negative.
"""Describe what and why, not how — the code shows how.
Type hints
Type hints (or annotations) state the types a function expects and returns:
def total(prices: list[float], tax: float = 0.2) -> float:
return sum(prices) * (1 + tax)name: typeafter each parameter;= defaultafter the type, if there is one;-> typebefore the colon for the return value (-> Nonefor functions that don’t return anything).
Common types
| Hint | Meaning |
|---|---|
int, float, str, bool |
the basic types |
list[str] |
a list of strings |
dict[str, float] |
a dict with string keys and float values |
tuple[int, int] |
a tuple of exactly two ints |
set[str] |
a set of strings |
str | None |
a string or None (an “optional” value) |
int | float |
either type |
Variables can be annotated too, though you rarely need to: scores: list[int] = [] helps when you start with an empty collection.
Hints are not checked at run time
This surprises many people:
def double(n: int) -> int:
return n * 2
print(double("ha")) # 'haha' — no error!Python ignores hints when running the code. They’re information for people and tools:
- Editors (VS Code with Pylance, PyCharm) use them to offer completions and underline mistakes as you type —
double("ha")gets a squiggle. - Type checkers such as mypy and pyright check a whole project without running it:
pip install mypy
mypy shop.pyshop.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]Catching that kind of mistake before the code ever runs is the big win, and it grows with the size of your project.
When to add hints
- Always on functions other people (or future you) will call.
- Not necessary on every local variable — type checkers work out most of them.
- Start simple; hints are optional and you can add them gradually.
Seeing hints and docstrings in code
Both are stored on the function object:
average.__doc__ # the docstring
average.__annotations__ # {'numbers': list[float], 'return': <class 'float'>}Tools like documentation generators and frameworks (FastAPI, for example, uses hints to validate web requests) read these attributes.
Habit to build: every function that’s more than a quick helper gets a one-line docstring and type hints. It takes ten seconds and saves minutes every time someone reads it.
Document a small library
The starter has three working but undocumented functions. Add a docstring and complete type hints to each: average takes a list of floats and returns a float; find_price takes a dict of str → float and a str, and returns a float or None; format_name takes a first name, an optional middle name (str or None, default None) and a last name passed by keyword, returning a str. Then print the first line of each function’s docstring using __doc__, and print average.__annotations__.
def average(numbers):
return sum(numbers) / len(numbers)
def find_price(prices, item):
return prices.get(item)
def format_name(first, middle=None, *, last):
if middle:
return f"{first} {middle[0]}. {last}"
return f"{first} {last}"
print(average([2.0, 4.0]))
print(find_price({"tea": 3.5}, "tea"), find_price({"tea": 3.5}, "pie"))
print(format_name("Ada", last="Lovelace"), format_name("John", "Fitzgerald", last="Kennedy"))def average(numbers: list[float]) -> float:
"""Return the arithmetic mean of a non-empty list of numbers."""
return sum(numbers) / len(numbers)
def find_price(prices: dict[str, float], item: str) -> float | None:
"""Return the price of item, or None if it isn't on the menu."""
return prices.get(item)
def format_name(first: str, middle: str | None = None, *, last: str) -> str:
"""Return a display name, abbreviating any middle name to an initial.
Example: format_name("John", "Fitzgerald", last="Kennedy") -> "John F. Kennedy"
"""
if middle:
return f"{first} {middle[0]}. {last}"
return f"{first} {last}"
print(average([2.0, 4.0]))
print(find_price({"tea": 3.5}, "tea"), find_price({"tea": 3.5}, "pie"))
print(format_name("Ada", last="Lovelace"), format_name("John", "Fitzgerald", last="Kennedy"))
for func in (average, find_price, format_name):
print(func.__name__, "-", func.__doc__.splitlines()[0])
print(average.__annotations__)Summary
- A docstring is a string literal on the first line of a function; it explains what the function does and shows in
help()and editors. - Type hints annotate parameters (
price: float) and return values (-> float). - Use built-in generics like
list[str]anddict[str, int], andX | Nonefor optional values. - Python doesn’t enforce hints at run time; editors and checkers such as mypy and pyright use them to find bugs early.
- Hints and docstrings are documentation for people as much as for tools — add them to every function others will use.