Sub topic 3
Extending TypedDicts and Choosing Related Tools
Assume you know Python dictionaries, functions, classes, and basic type checking with mypy or pyright. These examples use Python 3.11 or newer. ReadOnly requires Python 3.13 or typing_extensions.
Extending a TypedDict
A TypedDict can inherit required and optional keys from another TypedDict. The child adds fields while keeping the parent’s contract.
from typing import NotRequired, TypedDict
class User(TypedDict):
id: int
name: str
class Employee(User):
department: str
phone: NotRequired[str]
worker: Employee = {
"id": 7,
"name": "Mina",
"department": "Support",
}Inheritance describes a larger dictionary shape. It does not create a runtime subclass of dict.
Keys That Are Not Identifiers
Use functional syntax when a key is not a valid Python identifier, such as "user-id" or "class".
from typing import TypedDict
Record = TypedDict("Record", {"user-id": int, "class": str})
record: Record = {"user-id": 3, "class": "admin"}Compatibility Rules
TypedDict checking is structural. A value matches when it has compatible keys and value types, even if it uses a different TypedDict definition.
A TypedDict is commonly accepted where a read-only mapping is expected. It is generally not accepted as dict[str, object], because that function could insert keys or values that violate the TypedDict contract.
flowchart TD
A[TypedDict value] --> B[Read-only Mapping]
A --> C[Specific compatible TypedDict]
A -. unsafe mutation .-> D[dict[str, object]]Typing `**kwargs` with `Unpack`
Unpack connects keyword arguments to a TypedDict definition.
from typing import TypedDict, Unpack
class Options(TypedDict, total=False):
timeout: float
retries: int
def request(url: str, **options: Unpack[Options]) -> None:
print(url, options.get("timeout", 10.0))
request("https://example.com", timeout=2.5)A checker can reject unknown keyword names or incorrect value types.
Marking Keys ReadOnly
ReadOnly prevents reassignment according to the type checker. It does not freeze the dictionary at runtime.
from typing import ReadOnly, TypedDict
class Account(TypedDict):
id: ReadOnly[int]
balance: floatChoosing a Tool
| Tool | Best fit |
|---|---|
| `TypedDict` | JSON-like records passed between functions |
| `dataclass` | Application objects with behavior and defaults |
| Validation library | Untrusted input requiring runtime checks and conversion |
Choose a validation library at an API boundary. Choose TypedDict when static documentation of an existing dictionary is enough.
Exercise
Why might a TypedDict be accepted as a Mapping but not as a dict?
Show answer
A Mapping offers read-only access, while a dict may be mutated in ways that violate the TypedDict’s known keys and value types.