Python typehintテクニック

あるクラスの中でそのクラスを型として使用したい

  • pythonではクラス定義の中でそのクラス自身の名前を参照できない
  • 型定義もそれでエラーになる
class Dog:
    def me(self) -> Dog: # error
        ...
  • 解決策は型を文字列として指定してあげる
class Dog:
    def me(self) -> 'Dog': # success
        ...

インスタンスではなくクラスの型を指定したい

  • 普通に型指定するとインスタンスの型として認識される
class User: ...

def say(user: User): ...

say(User()) # ok
say(User) # bad
  • クラス自身の型を指定してあげたい場合はTypeキーワードを使う
class User: ...

def say(user: Type[User]): ...

say(User()) # bad
say(User) # ok

型をキャストしたいとき

  • cast関数を使う
from typing import cast

cast(int, "not int")

どうしても型を通せないとき

  • ignoreあります
  • コメントで書くとignoreされます
def complex_return_type(): ... # type: ignore
PythonのEllipsis(…)とtype hints PythonとNewType pyrightの使い方
View Comments
There are currently no comments.