CKTIS / Python
typing.TypedDict
Opiše shemo slovarja z znanimi besedilnimi ključi in lastnim tipom vrednosti za vsako polje.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
class Task(TypedDict): ...Opiše shemo slovarja z znanimi besedilnimi ključi in lastnim tipom vrednosti za vsako polje.
Privzeto so ključi brez NotRequired obvezni. Konstruktor brez preverjanja vrne navaden dict, isinstance z razredom TypedDict pa sproži TypeError. Od Pythona 3.13 ReadOnly označi statično nespremenljivo polje neodvisno od obvezne prisotnosti.
Slovar med izvajanjem zapis dovoli.
Primeri
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)
Rezultat
True {'x': 'other'} ['x', 'y']
no instance check
{'id': 2}Slovar med izvajanjem zapis dovoli.