CKTIS / Python
typing.TypedDict
Opisuje schému slovníka so známymi reťazcovými kľúčmi a vlastným typom hodnoty pre každé pole.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
class Task(TypedDict): ...Opisuje schému slovníka so známymi reťazcovými kľúčmi a vlastným typom hodnoty pre každé pole.
Predvolene sú kľúče bez NotRequired povinné. Konštruktor vráti bežný dict bez overenia a isinstance s triedou TypedDict vyvolá TypeError. Od Pythonu 3.13 označuje ReadOnly staticky nezmeniteľné pole nezávisle od povinnej prítomnosti.
Slovník za behu zápis dovolí.
Príklady
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)
Výsledok
True {'x': 'other'} ['x', 'y']
no instance check
{'id': 2}Slovník za behu zápis dovolí.