ID EN
Typing

TypedDict

Python 3.11 🇮🇩 Bahasa Indonesia

Konstruksi khusus untuk menambahkan petunjuk tipe ke kamus. Saat runtime, "Contoh TypedDict" hanyalah dicts.

Syntax

PYTHON
class typing.TypedDict(dict)

Contoh

Example 1
PYTHON
class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}   OK
b: Point2D = {'z': 3, 'label': 'bad'}            Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
Example 2
PYTHON
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
Example 3
PYTHON
Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Example 4
PYTHON
raises SyntaxError
class Point2D(TypedDict):
    in: int   'in' is a keyword
    x-y: int   name with hyphens

 OK, functional syntax
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
Example 5
PYTHON
class Point2D(TypedDict):
    x: int
    y: int
    label: NotRequired[str]

 Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})

See Also

dict dict identifiers NotRequired Required Generic Annotations Best Practices __total__