Sub topic 11
Compatibility rules: structural typing, Mapping and dict
This chapter explains which values a type checker accepts where a TypedDict is expected, and which other types a TypedDict can stand in for. It assumes you can define a TypedDict with class syntax, know that total and NotRequired control which keys are optional, and run mypy or pyright separately from your program. All the rules here are static. At runtime every example is an ordinary dict.
Structural typing: shape decides, not the name
A normal class is compatible with another class through inheritance, which is nominal typing. A TypedDict is different. One TypedDict is compatible with another when its keys have the right shape, even when the two classes are unrelated.
from typing import TypedDict
class Named(TypedDict):
name: str
class Employee(TypedDict):
name: str
salary: int
def greet(item: Named) -> str:
return f"Hello, {item['name']}"
emp: Employee = {"name": "Ada", "salary": 100}
print(greet(emp)) # accepted: Employee has every key Named needsEmployee does not inherit from Named. The checker accepts the call because every key in Named is present in Employee with the same type. Extra keys on the passed value are allowed, since greet only reads name.
The rule is about variables, not literals. A dict literal written directly where a TypedDict is expected is checked for exact keys:
from typing import TypedDict
class Named(TypedDict):
name: str
def greet(item: Named) -> str:
return f"Hello, {item['name']}"
print(greet({"name": "Ada"})) # accepted
print(greet({"name": "Ada", "salary": 100})) # rejected: unexpected key "salary"Both calls run normally. The second one is reported only by the checker. The extra key is flagged because a literal has no other name through which its extra data could be used. A variable of a wider TypedDict type is accepted because the checker knows its declared type.
The four conditions for compatibility
Type A is assignable to TypedDict type B when all of these hold:
- Every key in
Balso exists inA. - A key that is required in
Bis required inA. - A key that is not required in
Bis also not required inA. - Each shared key has the same value type in both.
Conditions 2, 3 and 4 surprise people, so each gets a closer look.
Value types must match exactly
A dict is mutable, so a function that receives a B may write to it. If value types could differ, that write could break the original.
from typing import TypedDict
class Age(TypedDict):
age: int
class MaybeAge(TypedDict):
age: int | None
def clear(person: MaybeAge) -> None:
person["age"] = None
a: Age = {"age": 3}
clear(a) # rejected: Age is not compatible with MaybeAge
print(a) # prints {'age': None}, which breaks the Age promiseThe program runs, and the last line shows the damage the checker prevented. Types that behave this way are called invariant. A list[int] is not accepted as a list[int | None] for the same reason.
A key declared ReadOnly (Python 3.13, or typing_extensions earlier) removes the risk, because nobody can write to it. For read-only keys the value type is allowed to be narrower in the source. That would make Age assignable to a MaybeAge whose age is ReadOnly[int | None].
Required-ness must match
Required-ness is also checked in both directions.
from typing import NotRequired, TypedDict
class Named(TypedDict):
name: str
class MaybeNamed(TypedDict):
name: NotRequired[str]
def forget(item: MaybeNamed) -> None:
item.pop("name", None) # legal for MaybeNamed
def read(item: Named) -> str:
return item["name"]
n: Named = {"name": "Ada"}
m: MaybeNamed = {}
forget(n) # rejected: forget could delete a required key
read(m) # rejected: the key may be missing
print(n, m)Passing Named to forget would let the function delete a key the original type promises. Passing MaybeNamed to read could raise KeyError. Both directions are unsafe, so both are rejected.
TypedDict and dict are different types
A TypedDict is not a subtype of dict[str, Any], dict[str, object], or any other dict[K, V]. The checker rejects this:
from typing import TypedDict
class Employee(TypedDict):
name: str
salary: int
def count_keys(data: dict[str, object]) -> int:
data["name"] = 42 # legal for dict[str, object]
return len(data)
emp: Employee = {"name": "Ada", "salary": 100}
print(count_keys(emp)) # rejected: Employee is not a dict[str, object]If this were allowed, count_keys would store an int in a str slot. The reverse direction fails too: a dict[str, object] cannot be passed where an Employee is expected, because the checker cannot know which keys it holds.
The Any form is a common stumbling block. Many people expect dict[str, Any] to accept anything, but the checker treats a TypedDict as a separate kind of type here. The usual fix is to change the parameter, not the caller.
Mapping is the read-only bridge
collections.abc.Mapping has no __setitem__, pop or del, so none of the dangers above apply. A TypedDict is compatible with Mapping[str, object]:
from collections.abc import Mapping
from typing import TypedDict
class Employee(TypedDict):
name: str
salary: int
def show(data: Mapping[str, object]) -> None:
for key, value in data.items():
print(key, value)
emp: Employee = {"name": "Ada", "salary": 100}
show(emp) # acceptedThe value type must be object. A function that wants to read any TypedDict generically, for example to log it or serialize it, should take Mapping[str, object].
The checker does not accept Mapping[str, int] even when every declared value is an int:
from collections.abc import Mapping
from typing import TypedDict
class Counts(TypedDict):
apples: int
pears: int
def total(data: Mapping[str, int]) -> int:
return sum(data.values())
counts: Counts = {"apples": 2, "pears": 3}
print(total(counts)) # rejected, although it prints 5 at runtimeThe reason is the structural rule from the first section. A value of a wider type, such as a Counts subtype with an extra label: str key, would still be passed in, and data.values() would then include a string. To avoid that, read the known keys directly (counts["apples"] + counts["pears"]) or copy them into a dict[str, int] first.
Summary of the rules
The table shows what the checker accepts for a source value of type Employee (keys name: str and salary: int).
| Target type | Accepted? | Reason | Column |
|---|---|---|---|
| `Named` (`name: str`) | Yes | Extra keys on a variable are fine | |
| `Employee` literal with an extra key | No | Literals are checked for exact keys | |
| TypedDict with `name: str \ | None` | No | Value types are invariant |
| TypedDict with `name: NotRequired[str]` | No | Required-ness must match | |
| `Mapping[str, object]` | Yes | Read-only, values seen as `object` | |
| `Mapping[str, int]` | No | Extra keys could hold other types | |
| `dict[str, object]` or `dict[str, Any]` | No | `dict` is mutable and untyped per key |
The diagram shows the same relationships as a decision path.
Nothing here is checked at runtime
All of these rules exist only for the type checker. At runtime a TypedDict value is a plain dict, so any dict function works on it. The TypedDict class itself cannot be used with isinstance:
from typing import TypedDict
class Named(TypedDict):
name: str
item: Named = {"name": "Ada"}
print(isinstance(item, dict)) # True
try:
isinstance(item, Named)
except TypeError as error:
print("TypeError:", error)The first check prints True. The second raises TypeError, because a TypedDict does not describe a runtime class. To find out whether data has the right shape at runtime, you need your own checks or a validation library. The last chapter of this tutorial compares those options.
Practical advice
- Prefer a narrow TypedDict as a parameter type when a function reads only a few keys. Any wider TypedDict value then works, with no inheritance needed.
- Use
Mapping[str, object]for generic read-only helpers. Usedict[str, object]only when you also need to modify the argument, and then the caller must pass a realdict. - When the checker reports an incompatibility between two TypedDicts, compare required-ness and value types before suspecting missing keys. These are the two most frequent causes.
Exercise
A function is declared def f(x: dict[str, object]) -> None. You have a variable p: Point where Point is a TypedDict with keys x: int and y: int. Why does the checker reject f(p), and what change to the function's signature allows the call if f only reads values?
Show answer
dict[str, object] is mutable, so f could store a value of any type under a key such as "x" and break the Point promise that it holds an int. A TypedDict is therefore not a subtype of any dict[K, V]. If f only reads, change the parameter to Mapping[str, object], which has no write methods, and the call is accepted.
Exercise
Given class A(TypedDict): id: int and class B(TypedDict): id: int; tag: str, which of these is accepted by a checker: passing a B variable to a parameter of type A, or passing an A variable to a parameter of type B? Explain.
Show answer
Passing a B variable to a parameter of type A is accepted. B has every key of A with the same value type, and the extra key tag is allowed on a variable. Passing an A variable to a B parameter is rejected because A has no tag key, so a read of tag could fail.