CKTIS / Python
typing.TypedDict
Describe a dictionary schema with known string keys and a separate value type for each.
Version: Python 3.14; repository image, production runtime not attested
Syntax
class Task(TypedDict): ...Describe a dictionary schema with known string keys and a separate value type for each.
Keys declared in a default total class are required unless individually marked NotRequired. A type checker checks the schema, but the constructor creates an ordinary dict and performs no validation. Using the TypedDict class as the second argument of isinstance raises TypeError. Since Python 3.13 ReadOnly separately marks a key that a type checker should forbid changing, independently of whether it must be present.
The ordinary dictionary still allows the write.
Examples
from typing import TypedDict
class Point(TypedDict):
x: int
y: int
point = Point(x="other")
print(type(point) is dict, point, sorted(Point.__required_keys__))
try:
isinstance(point, Point)
except TypeError:
print("no instance check")
from typing import NotRequired, ReadOnly
class Label(TypedDict):
id: ReadOnly[int]
note: ReadOnly[NotRequired[str]]
label: Label = {"id": 1}
label["id"] = 2
assert Label.__readonly_keys__ == {"id", "note"}
assert Label.__required_keys__ == {"id"} and Label.__optional_keys__ == {"note"}
print(label)
Result
True {'x': 'other'} ['x', 'y']
no instance check
{'id': 2}The ordinary dictionary still allows the write.