Pythonの辞書への型導入
Python辞書に対して型を導入してみた。
mypyを用いて型チェックは行える。
pythonのランタイム実行時には型チェックはされない。
github.com
from typing import Literal, TypedDict, Required, NotRequired class Apple(TypedDict, total=False): name: Required[Literal['apple']] applePiePrice: NotRequired[int] class Orange(TypedDict, total=False): name: Required[Literal['orange']] orangePiePrice: NotRequired[int] Fruit = Apple | Orange fruit1: Fruit = {'name': 'apple', 'orangePiePrice': 4} # NG # error: Incompatible types (expression has type "Literal['apple']", TypedDict item "name" has type "Literal['orange']") [typeddict-item] fruit2: Fruit = {'name': 'apple', 'applePiePrice': 4} # OK fruit3: Fruit = {'name': 'apple'} # NG # error: Type of TypedDict is ambiguous, could be any of ("Apple", "Orange") [misc] # error: Incompatible types in assignment (expression has type "Dict[str, str]", variable has type "Union[Apple, Orange]") [assignment] fruit4: Apple = {'name': 'apple'} # OK
TypeScriptみたいな強力な予測は効かないみたい?
この場合、applePiePriceが予測に出てくれると嬉しいが。。
いい感じのVSCode拡張とかありましたら教えてください。