Sub topic 2
Annotating functions and variables
This chapter assumes you can write Python 3.10+ functions and classes, and that you have a virtual environment where you can install packages. You do not need to have run a type checker yet. The next chapter covers that.
What an annotation is
An annotation is a piece of syntax that records the type you expect a name to hold. Python stores annotations but does not enforce them when the program runs. A static checker such as mypy or Pyright reads them and compares them with how you actually use the values.
Annotating functions
Put a colon and a type after each parameter. Put -> and a type before the final colon to describe the return value.
def greet(name: str) -> str:
return "Hello, " + name
greet("Ada")
greet(42) # flagged by the checker: int is not strThe annotations declare that greet takes a str and returns a str. Both mypy and Pyright report the call with an int argument without running the program. At runtime, Python would only fail when the + operation executes.
A function that returns nothing is annotated -> None. Without a return annotation, a checker treats the function as unannotated and may skip checking its body.
Annotating variables
Write the type after the variable name:
count: int = 0
names: list[str] = []
ratio: floatThe last line declares a type without assigning a value. Often you do not need a variable annotation, because the checker infers the type from the assigned value. Add one when the value alone is not enough. An empty list is a common case, since the checker cannot tell what it will hold.
Class attributes
Annotate attributes in the class body, or assign them in __init__:
class Account:
owner: str
balance: float = 0.0
def __init__(self, owner: str) -> None:
self.owner = owner
def deposit(self, amount: float) -> None:
self.balance += amountAnnotate every parameter of __init__ except self. The checker already knows the type of self.
Common built-in types
| Annotation | Meaning |
|---|---|
| `int`, `str`, `bool`, `float` | Plain scalar values |
| `list[int]` | A list whose items are all `int` |
| `dict[str, int]` | A dict with `str` keys and `int` values |
| `tuple[int, str]` | A tuple of exactly two items, in that order |
| `tuple[int, ...]` | A tuple of any length, all `int` |
| `set[str]` | A set of strings |
On Python 3.9 and newer you can use the built-in names such as list and dict directly. You no longer need List and Dict from typing.
Common mistakes
- Leaving off a return annotation and expecting the body to be checked. Annotate the signature fully.
- Writing
listwith no item type. It works, but the checker then knows little about the items. - Annotating
__init__with-> stror another type. It must be-> None. - Assuming annotations validate input at runtime. Data from files or the network can still have the wrong type.
Exercise
A function is written as def total(prices: list[float]) -> float:. What happens if you call total(["a", "b"]), and when is the problem reported?
Show answer
A static checker reports that list[str] is not compatible with list[float] before the program runs. Python itself does not check the annotation. The call only fails at runtime if the function body does something invalid with strings, such as adding them to a number.
Exercise
Why might you annotate items: list[int] = [] instead of writing items = []?
Show answer
An empty list gives the checker no information about its contents. The annotation states that the list holds int values, so later append calls with other types can be flagged.