Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

typing.TypedDict

Opisuje shemu rječnika s poznatim tekstnim ključevima i zasebnim tipom vrijednosti po polju.

Verzija: Python 3.14; repository image, production runtime not attested

Sintaksa

class Task(TypedDict): ...

Opisuje shemu rječnika s poznatim tekstnim ključevima i zasebnim tipom vrijednosti po polju.

Zadano su ključevi bez NotRequired obvezni. Konstruktor bez provjere vraća obični dict, a isinstance s klasom TypedDict izaziva TypeError. Od Pythona 3.13 ReadOnly označava statički nepromjenjivo polje neovisno o obveznoj prisutnosti.

Rječnik pri izvršavanju dopušta upis.

Primjeri

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}

Rječnik pri izvršavanju dopušta upis.

Izvori