What is TypedDict?
Python programs often use dictionaries with string keys to represent objects.TypedDict lets you give precise types for dictionaries with a fixed schema:
The type annotation is important — without it, mypy will infer a regular
dict type.Why use TypedDict?
Regulardict[K, V] types require all values to have the same type. TypedDict allows each key to have an independent value type:
Type checking with TypedDict
Mypy validates keys and value types:Class-based syntax
An alternative, class-based syntax is available (Python 3.6+):The class-based syntax doesn’t define a real class. It’s just a type definition.
TypedDict inheritance
The class-based syntax supports inheritance:Totality
By default, all keys are required. Usetotal=False to make keys optional:
- Required keys (default)
- Optional keys
Optional keys are shown with a
? in error messages: {'language'?: str, 'color'?: str}Mixing required and optional keys
Use inheritance to mix required and optional keys:Read-only items
UseReadOnly to mark TypedDict items as read-only:
Supported operations
TypedDict objects support a subset of dictionary operations:Mapping operations
Mapping operations
d[key]— Get itemkey in d— Check membershiplen(d)— Get lengthfor key in d— Iterationd.get(key[, default])— Get with defaultd.keys(),d.values(),d.items()— Views
Mutation operations
Mutation operations
d.copy()— Shallow copyd.setdefault(key, default)— Set defaultd1.update(d2)— Update from another dictd.pop(key[, default])— Pop key (partial TypedDicts only)del d[key]— Delete key (partial TypedDicts only)
Using as constructor
The TypedDict type object can act as a constructor:Structural compatibility
Mypy uses structural compatibility with TypedDicts. A TypedDict with extra items is compatible with a narrower TypedDict:TypedDict and Mapping
Any TypedDict is compatible withMapping[str, object]:
A TypedDict object is not a subtype of
dict[str, ...] since dict allows arbitrary keys to be added and removed.Unions of TypedDicts
Use the tagged union pattern to distinguish between different TypedDict variants:Inline TypedDict types
Mypy supports experimental inline TypedDict syntax:Best practices
Use class-based syntax
Use class-based syntax
The class-based syntax is more readable and supports inheritance.
Annotate variables
Annotate variables
Always provide explicit type annotations when creating TypedDict objects to avoid inference issues.
Use tagged unions
Use tagged unions
For discriminated unions, add a literal-typed tag field to enable type narrowing.
Prefer total=True
Prefer total=True
Making keys required by default helps catch missing data early.