Sub topic 11
Compatibility rules: structural typing, Mapping and dict
This chapter assumes you can define a TypedDict, know the difference between required and NotRequired keys, and run a checker such as mypy or pyright. Here you learn when a checker accepts one TypedDict where another is expected, and why a TypedDict does not fit dict[str, Any].
Structural, not nominal
Two classes with different names are unrelated in nominal typing, even when their contents match. TypedDict uses structural typing. A checker compares keys, value types and required-ness, and ignores the class name or inheritance.
from typing import TypedDict
class Person(TypedDict):
name: str
class Employee(TypedDict):
name: str
company: str
def greet(person: Person) -> str:
return f"Hello, {person['name']}"
employee: Employee = {"name": "Ada", "company": "Analytical Engines"}
print(greet(employee)) # accepted: Employee has every key Person needsEmployee does not inherit from Person, yet the call is accepted. An Employee has everything a Person requires, so it is a subtype. Extra keys are allowed because a function that only reads name cannot be harmed by them.
The rules
A TypedDict A is compatible with B when all of these hold:
| Rule | Example of a mismatch |
|---|---|
| `A` has every key of `B` | `A` lacks `name` |
| Value types are the same for each shared key | `A` has `id: int`, `B` has `id: float` |
| Each key is required in `A` if it is required in `B` | `A` marks `name` as `NotRequired` |
| A key that is `NotRequired` in `B` is also `NotRequired` in `A` | `A` makes it required |
The type rule is strict because dictionaries are mutable. If A with id: int were accepted as B with id: float, a function could store 1.5 through the B view and break the original. The same reasoning explains the required-ness rules: through the B view, code could delete a key that A promises is present. Marking a key ReadOnly relaxes these rules, because the key can no longer be changed through that view.
Mapping and dict
A TypedDict is compatible with Mapping[str, object]. It is not compatible with dict[str, object] or dict[str, Any].
from collections.abc import Mapping
from typing import Any, TypedDict
class Point(TypedDict):
x: int
y: int
def show_keys(data: Mapping[str, object]) -> None:
print(sorted(data))
def clear_all(data: dict[str, Any]) -> None:
data.clear()
p: Point = {"x": 1, "y": 2}
show_keys(p) # accepted: read-only view
clear_all(p) # rejected by a type checker, runs normally
print(p)Mapping only reads. Reading values as object is safe, because every value is at least an object. dict allows writing any key and value, which could break the declared shape, so checkers refuse it. The call to clear_all still empties p at runtime, because nothing is enforced there.
The practical advice is to annotate read-only parameters as Mapping[str, object] when a function should accept any TypedDict. For a single known shape, use that TypedDict.
Common errors
- Passing a
TypedDictto a function annotateddict[str, Any]. Change the parameter toMapping[str, object], or to theTypedDictitself. - Expecting
intto be accepted for afloatkey. Numeric widening does not apply to mutable keys. - Assuming an extra key is always safe. It is safe for reading. With a literal, a checker may still report unknown keys, as in
greet({"name": "Ada", "company": "X"}), because a dict literal is checked against the exact declared shape.
Exercise
A function is annotated def total(data: dict[str, int]) -> int. You call it with a variable of type class Scores(TypedDict): math: int; art: int. A checker rejects the call. Give one change to the function signature that fixes it, and say why the original was rejected.
Show answer
Change the parameter to Mapping[str, int]. A TypedDict is compatible with Mapping[str, int] when all its values are int, because a Mapping cannot be written to. The original dict[str, int] was rejected because a dict is mutable and could receive any new string key, which would break the fixed shape of Scores.