🐥

Pythonのdictに型付けする

2023/03/31に公開

きっかけ

本題

from typing import TypedDict

class ObjectType(TypedDict):
    id: int
    name: str

class RequestType(TypedDict):
    foo: str
    bar: ObjectType

def get(self, args: RequestType) -> None:
    foo = args['foo'] # type: str
    bar = args['bar'] # type: ObjectType
    name = args['bar']['name'] # type: str

まとめ

  • TSと似た感覚で型付けができます!
  • typingにはこれ以外にも多くの型ヒントが定義されていますので一度目を通すと参考になるかと思います

Discussion