Python Glossary Русский

Python 3.8+Annotations & typingterm

typing.TypedDict

typeddict

A dictionary with a fixed set of typed keys. For static analysis only; at runtime it is an ordinary dict.

Syntax

from typing import TypedDict
class MyDict(TypedDict):
    key: type

The main trap: nothing is checked at runtime — an extra key, a missing key or a string where a float was declared all pass silently, and only mypy or another static checker will complain. It is not a real class: you build it as a plain dict literal, read it as p['x'] rather than p.x, and isinstance against a TypedDict is not allowed. Reach for it when the data already arrives as a dict (JSON from an API, a config); if you design the structure yourself, a dataclass or NamedTuple with real attributes is usually nicer. The functional form without a field dict — TypedDict('TD') or TypedDict('TD', None) — was deprecated in 3.13 and is disallowed from 3.15: write an empty type as TypedDict('TD', {}).

Examples

from typing import TypedDict
class Point(TypedDict):
    x: float
    y: float
p: Point = {'x': 1.0, 'y': 2.0}
print(p['x'])  # → 1.0
print(p['y'])  # → 2.0
from typing import TypedDict
class User(TypedDict, total=False):
    name: str
    age: int
u: User = {'name': 'Alice'}  # → age необязателен
print(u)  # → {'name': 'Alice'}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy