python3.5の型ヒントでジェネリクス型を定義

型ヒントによる構文チェックの基本については、こちらを参照。Python3.5以降のみ使用可能。

python3.5以降の型ヒント(typeing)の使用 – 基本

ジェネリクス(コンテナ内の型明示)

Java言語のようにジェネリクスを使ってコンテナ内のオブジェクトの型情報を明示することができる。

from typing import List

a:List[str] = []   # 文字列を格納するlistであることを明示
a.append("hello")
a.append(1)        #! Argument 1 to "append" of "list" has incompatible type "int"; expected "str"

型変数

TypeVarを使って型変数を定義できる。

intのListを渡すと返り値はintになるので型チェックできる。

from typing import TypeVar, Sequence
T = TypeVar('T')
def firstElement(l: Sequence[T]) -> T:   # List[T]の最初の要素を返すので戻り値はT型
    return l[0]
firstElement([1, 2, 3])+" " # Unsupported operand types for + ("int" and "str")

クラス定義時のジェネリッククラス

型変数をクラス定義に設定し、インスタンス生成時に型定義を明示する。

from typing import TypeVar, Generic

T = TypeVar('T')
class MyContainer(Generic[T]):   # MyContainerはT型のジェネリックスクラスとする
    def set(self, v:T):
        self.value:T = v
    def get(self) -> T:
        return self.value

container = MyContainer[int]()   # int型のMyContainerを生成
container.set(1)
container.get() + 3

container.set("Hello")      # ! Argument 1 to "set" of "MyContainer" has incompatible type "str"; expected "int" 
container.get().index("l")  # ! "int" has no attribute "index"

参考:26.1.4. ジェネリクス

関連記事:

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)