typing.TypedDict
https://docs.python.org/ja/3/library/typing.html#typing.TypedDict
#Python_typing
PEP 589 – TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys
Python 3.8〜
Special construct to add type hints to a dictionary. At runtime it is a plain dict.
「実行時はただの辞書」
型チェックを追加した辞書という理解
例
code: python
class Point2D(TypedDict):
x: int
y: int
label: str
# 初期化する方法2通り
a = {'x': 1, 'y': 2, 'label': 'good'}
b = Point2D(x=1, y=2, label='first')
オプションのキー
total=Falseを指定する
total=Falseを指定したTypedDictで必須のキーを表す
class DicthasOptionalKey(RequiredKeysTypedDict, total=False)
The functional syntax should also be used when any of the keys are not valid identifiers, for example because they are keywords or contain hyphens.
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})