Skip to main content
TypedDict is a type hint construct from the typing module used to specify the expected types of values associated with specific string keys in a dictionary. It provides structural type information to static type checkers (such as mypy or pyright) without altering the runtime behavior of the dictionary. At runtime, an instance of a TypedDict is a standard Python dict, and no type validation or enforcement occurs.

Syntax

TypedDict can be defined using two syntaxes: the class-based syntax (preferred for readability) and the alternative assignment syntax (required when dictionary keys are not valid Python identifiers or are reserved keywords).

Runtime Behavior

TypedDict is strictly a static typing tool subject to type erasure. Instantiating a TypedDict creates a standard dictionary. It does not enforce types, restrict extra keys, or provide default values during execution.

Totality and Key Presence

By default, a TypedDict is total, meaning every key defined in the type definition must be present in the dictionary instance. You can modify this behavior at the class level using the total parameter, or at the granular key level using Required and NotRequired (introduced in Python 3.11 via PEP 655).

Class-Level Totality

Setting total=False makes all keys in the dictionary optional.

Key-Level Totality (Python 3.11+)

NotRequired marks specific keys as optional within a total TypedDict. Conversely, Required marks specific keys as mandatory within a non-total (total=False) TypedDict.

Inheritance

TypedDict supports multiple inheritance, allowing the composition of complex dictionary types from simpler ones. A subclass inherits all key-type pairs from its base classes. If multiple base classes define the same key, the type annotations for that key must match exactly, otherwise static type checkers will report a conflict.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More