Show contents
Chapter 1 of 7 · 20 min
Type annotations
By the end of this chapter, you'll be able to
- Annotate a function's parameters and return value, including optional values
- Describe structures with list, dict, TypedDict and dataclasses
- Define an interface contract with typing.Protocol
- Explain why Python doesn't check types at run time and how mypy does
Annotating a function
You annotate a parameter with : type and the return value with -> type. Since Python 3.10, A | B means "A or B":
from typing import TypedDict, Protocol
def average(grades: list[float]) -> float | None:
if not grades:
return None
return sum(grades) / len(grades)
print(average([12.0, 15.5]), average([]))
print(average.__annotations__)
class Book(TypedDict):
title: str
year: int
def summary(book: Book) -> str:
return f"{book['title']} ({book['year']})"
print(summary({"title": "So Long a Letter", "year": 1979}))
print(average(["twelve"]) if False else "annotations aren't checked at run time")
13.75 None
{'grades': list[float], 'return': float | None}
So Long a Letter (1979)
annotations aren't checked at run time
list[float],dict[str, int],tuple[int, int],set[str]describe the content of collections;float | Noneclearly says the function may return nothing: the caller must handle that case;TypedDictdescribes a dictionary's expected keys; for an object with behaviour, a dataclass is better;- annotations are stored in
__annotations__, but Python never checks them at run time.
An interface contract: Protocol
A Protocol describes what an object can do, without imposing inheritance. Any object with the right methods fits: it's duck typing ("if it quacks like a duck…"), but checkable by a tool.
from typing import Protocol
from dataclasses import dataclass
class Notifiable(Protocol):
def send(self, message: str) -> str: ...
@dataclass
class Sms:
number: str
def send(self, message: str) -> str:
return f"SMS to {self.number}: {message}"
@dataclass
class Email:
address: str
def send(self, message: str) -> str:
return f"E-mail to {self.address}: {message}"
def notify(channels: list[Notifiable], message: str) -> None:
for channel in channels:
print(channel.send(message))
notify([Sms("+233 20 000 0000"), Email("contact@example.org")], "Your order is ready")
SMS to +233 20 000 0000: Your order is ready
E-mail to contact@example.org: Your order is ready
Sms and Email inherit from nothing: they satisfy the protocol because they have a send(str) -> str method. notify only depends on the contract, not on concrete classes. We'll come back to this in the final project.
Checking with mypy
On your machine, mypy reads the annotations and reports inconsistencies, without running the program:
def total(prices: list[float]) -> float:
return sum(prices)
total(["3", "4"])
average([10.0]) + 1
$ mypy orders.py
orders.py:4: error: List item 0 has incompatible type "str"; expected "float"
orders.py:5: error: Unsupported operand types for + ("None" and "int")
Found 2 errors in 1 file (checked 1 source file)
The second error is precious: average can return None, and mypy reminds you of it everywhere you forget that case. Run it in your CI, like the tests.
The error only appears at run time, and only if that line is reached.
Text description of the animation
- A call passes strings to a function that expects numbers.
- mypy spots the error without running the code: you fix it before even launching the program.
- Without mypy, Python runs the call as is: annotations are only documentation to it.
- The error only appears at run time, and only if that line is reached.
Your turn
Worked exercise
Worked exercise: typing a small module
Fully annotate these functions from a currency module: convert(amount, rate) returns a float; known_rate(currency, rates) returns a currency's rate from a dictionary, or None if it's unknown; summary(conversions) receives a list of pairs (currency, amount) and returns a text. Then write a function convert_if_known that uses known_rate and handles the None case properly.
Hint 1
dict[str, float], a list of pairs list[tuple[str, float]].Hint 2
float | None return, test if rate is None: before using the value: that's exactly what mypy requires.Show the solution and common mistakes
def convert(amount: float, rate: float) -> float:
return round(amount * rate, 2)
def known_rate(currency: str, rates: dict[str, float]) -> float | None:
return rates.get(currency)
def summary(conversions: list[tuple[str, float]]) -> str:
return ", ".join(f"{amount} {currency}" for currency, amount in conversions)
def convert_if_known(amount: float, currency: str, rates: dict[str, float]) -> float | None:
r = known_rate(currency, rates)
if r is None:
return None
return convert(amount, r)
RATES = {"XOF": 655.957, "MAD": 10.9}
print(convert_if_known(20, "XOF", RATES), convert_if_known(20, "JPY", RATES))
print(summary([("XOF", 13119.14), ("MAD", 218.0)]))
13119.14 None
13119.14 XOF, 218.0 MAD
Common mistakes:
- Writing
-> floatforknown_rate: it's wrong as soon as the currency is unknown, and mypy can no longer warn you when theNonecase is forgotten. - Testing
if not r:instead ofif r is None:: a rate of0.0would be treated as an unknown currency.
Summary
- 1You annotate with param: type and -> type; A | None marks an optional value.
- 2list[float], dict[str, int], TypedDict and dataclasses describe structures.
- 3A Protocol describes what an object can do, without imposing inheritance.
- 4Python ignores annotations at run time; mypy checks them beforehand.
- 5Data coming from outside must always be validated on the way in.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.