Sub topic 4
Annotating lists, dicts, sets, and tuples
This chapter assumes you can write Python functions and use list, dict, set, and tuple. It also assumes you have seen the basic name: type syntax and can run mypy or pyright. Here you learn how to describe what a collection holds, not only that it is a collection.
Built-in generic types
A bare list annotation says little. A checker accepts any element type and cannot catch scores[0].upper() on a list of numbers. Since Python 3.9 you can subscript the built-in types directly to name the contents:
list[int]is a list whose items are allint.dict[str, int]is a dict withstrkeys andintvalues.set[str]andfrozenset[str]holdstritems.
def average(scores: list[float]) -> float:
return sum(scores) / len(scores)
ages: dict[str, int] = {"Ada": 36, "Linus": 55}
tags: set[str] = {"python", "typing"}
print(average([90.5, 80.0]))
print(ages["Ada"], sorted(tags))A type that takes parameters in square brackets is called a generic type. The bracketed part is the type argument.
Code written for Python 3.8 or earlier used List, Dict, and Set imported from typing. Those names still work but are deprecated aliases. Use the lowercase built-ins unless you must support an old interpreter.
Annotating empty collections
A checker infers the element type from the values you put in. An empty literal gives it nothing to infer from, so you usually need to annotate it:
def group_by_length(words: list[str]) -> dict[int, list[str]]:
groups: dict[int, list[str]] = {}
for word in words:
groups.setdefault(len(word), []).append(word)
return groups
print(group_by_length(["a", "bb", "cc"]))Without the annotation on groups, mypy reports Need type annotation for "groups". Pyright infers a type from later use in some cases, but an explicit annotation is clearer in both tools.
Annotations nest. dict[int, list[str]] reads as "a dict from int to a list of str".
Tuples are different
A list is usually homogeneous and can have any length. A tuple is often a fixed-size record whose positions have different types. The syntax reflects that:
point: tuple[int, int] = (3, 4)
record: tuple[str, int, bool] = ("Ada", 36, True)
scores: tuple[int, ...] = (90, 85, 77)
empty: tuple[()] = ()
def min_max(values: list[int]) -> tuple[int, int]:
return min(values), max(values)
low, high = min_max([4, 2, 9])
print(low, high, point, record, scores, empty)| Annotation | Meaning |
|---|---|
| `tuple[int, int]` | Exactly two `int` items |
| `tuple[str, int, bool]` | Exactly three items, with these types by position |
| `tuple[int, ...]` | Any number of `int` items, including zero |
| `tuple[()]` | The empty tuple |
The literal ... (an ellipsis) means "any length" and only works as the second argument of a one-type tuple. Writing tuple[int] is a common mistake. It means a tuple of exactly one int, not a tuple of any length. A checker also flags indexing past the end of a fixed-size tuple, such as point[2].
Choosing parameter and return types
A function that only reads a collection does not need a list. If you annotate the parameter as list[str], callers cannot pass a tuple or a set, even though your code would work with them. The abstract types in collections.abc describe behavior instead of a concrete class:
| Type | What the function may do with it |
|---|---|
| `Iterable[T]` | Loop over it once |
| `Sequence[T]` | Index, slice, `len()`, loop. Lists, tuples, and `str` qualify |
| `Mapping[K, V]` | Read keys and values. Any dict qualifies |
| `list[T]`, `dict[K, V]` | Modify it in place |
A common guideline is to accept the most general type that supports what you do, and return a concrete type:
from collections.abc import Iterable, Mapping
def total_price(prices: Mapping[str, float], items: Iterable[str]) -> float:
return sum(prices[item] for item in items)
print(total_price({"tea": 2.5, "milk": 1.2}, ("tea", "milk")))Here a caller can pass a tuple, a list, or a generator for items. The return type is the concrete float.
Why list[int] is not list[object]
Mutable collections are invariant. That means list[str] is not accepted where list[object] is expected, even though str is an object. The reason is that the function could append a non-str item to your list. Read-only types such as Sequence are covariant, so they accept this.
from collections.abc import Sequence
def show_all(items: Sequence[object]) -> None:
for item in items:
print(item)
def append_marker(items: list[object]) -> None:
items.append(object())
names: list[str] = ["Ada", "Grace"]
show_all(names) # accepted: Sequence is read-only
append_marker(names) # checker error: list is invariantPython runs this file without complaint. Only the checker reports the last line, with a message like Argument 1 has incompatible type "list[str]"; expected "list[object]". The error is correct. After the call, names would hold an object, which breaks the promise that it holds only str.
If you hit this error, first ask whether the function really mutates the argument. If it does not, switch the parameter to Sequence or Iterable.
Mixed contents
Sometimes a dict holds values of several types. You can use a union as the value type:
config: dict[str, int | str] = {"host": "localhost", "port": 8080}
port = config["port"]
if isinstance(port, int):
print(port + 1)Every read now yields int | str, so you must narrow the value before using it. This gets tedious when the same keys always carry the same types. A fixed set of keys is better described with a TypedDict, covered in a later chapter.
Common errors
- Forgetting the type argument.
listalone is treated aslist[Any]. Strict modes, such as mypy's--strict, report this. - Using
tuple[int]for a variable-length tuple. Writetuple[int, ...]. - Annotating a parameter as
listwhen it is only read. Callers with tuples or sets get needless errors. - Using
[]or{}as a mutable default value. This is a runtime bug that annotations do not fix. UseNoneas the default and create the collection inside the function. - Using
list[int]on Python 3.8. It raisesTypeError: 'type' object is not subscriptablewhen the annotation is evaluated. Upgrade, or addfrom __future__ import annotations, which delays evaluation. Postponed evaluation is covered in a later chapter.
Exercise
A function def count_words(words: list[str]) -> dict[str, int] is called with count_words(("a", "b", "a")), and the checker reports an error. What change to the signature fixes it, and why is it safe?
Show answer
Change the parameter to Iterable[str] (or Sequence[str]), imported from collections.abc. The function only loops over words and never modifies it. Tuples are not lists, so list[str] rejects them. The abstract type accepts lists, tuples, and sets alike.
Exercise
Write annotations for a variable rgb holding exactly three int values, and for a variable history holding any number of float values in a tuple. Which one would a checker flag if you assigned a four-item tuple?
Show answer
rgb: tuple[int, int, int] and history: tuple[float, ...]. The checker flags the four-item tuple assigned to rgb, because that type has a fixed length of three. history accepts any length.