Typed API records
Representing JSON-like records returned by an API while preserving key and value expectations for static analysis.
Python · Class
TypedDict describes the expected keys and value types of dictionary-shaped data for static type checking. At runtime, values remain ordinary dictionaries and the constraints are not enforced by Python itself.
TypedDict describes the expected keys and value types of dictionary-shaped data for static type checking. It does not create a runtime container class: instances remain ordinary dict objects, and the declared constraints are not enforced during execution.
class User(TypedDict):
key: value_type
User = TypedDict('User', {'key': value_type}, total=True)| Name | Type | Description |
|---|---|---|
typename | str | The name of the TypedDict type when using functional syntax. |
fields | dict | A literal dictionary mapping field names to their expected types in functional syntax. |
total | bool | Whether keys defined in the TypedDict are required; the default is True. |
A TypedDict type declaration used by type checkers; instances are ordinary dict objects.
from typing import NotRequired, TypedDict
class User(TypedDict):
name: str
email: str
nickname: NotRequired[str]
user: User = {"name": "Ada", "email": "ada@example.com"}
print(user["name"])
Defines a dictionary shape for static type checkers while retaining an ordinary dictionary at runtime.
Representing JSON-like records returned by an API while preserving key and value expectations for static analysis.
Describing configuration or event dictionaries whose fields have a known schema.
Allowing some fields to be absent while keeping precise types for fields that are present.
TypedDict is a typing construct for describing dictionaries with a fixed set of named keys and associated value types. At runtime, its instances are ordinary dict objects, and type checkers enforce the declaration rather than Python itself.
Follow-up: How would you represent a key that may be absent? Use NotRequired for that key; this changes requiredness, not the value type itself.
Class syntax declares the keys as annotated attributes, for example class User(TypedDict): name: str. The functional form TypedDict('User', {'name': str}) is useful when key names are not valid Python identifiers.
Follow-up: Why might the functional form be necessary? It can represent names containing characters such as hyphens or names that would otherwise be affected by name mangling.
By default, declared keys are required. Individual keys can be made non-required with NotRequired, while the totality setting can control whether keys are required across a definition.
Follow-up: How can an inherited TypedDict mix required and non-required keys? Define a base TypedDict with one totality and inherit it in another definition with the other totality, or use per-key requiredness markers.
typing.NotRequiredtyping.Requiredtyping.is_typeddicttyping.get_type_hints