本文へスキップ

Pythonのget_type_hintsとget_argsで型ヒントを取得する

python-get-type-hints

get_type_hints・get_origin・get_argsとは

typing.get_type_hintsは、関数やクラスの型ヒントを実行時に取得する関数である。
文字列の注釈は型のオブジェクトに変換される。
typing.get_originとtyping.get_argsは、list[int]を外側の型のlistと型引数のタプル(int,)に分解する。
get_type_hints はPython 3.5から、get_originとget_args は3.8からtypingにある。

  • __annotations__の値は、from __future__ import annotationsか引用符の注釈では文字列で、isinstanceの引数に指定するとTypeErrorになる
  • get_type_hintsの結果は、文字列の注釈を評価し、基底クラスの注釈も統合した辞書である
    • 引用符の注釈で参照する関数の中のクラスは、名前とクラスの辞書を引数localnsに指定する必要がある
    • 評価の後もlist[int]はisinstanceの引数に指定できない
  • get_originとget_argsの結果で分岐すると、list[int]やint | Noneの型ヒントに対応する値の判定を実装できる
    • Callable[[int], str]の型引数は引数の型のリストと戻り値の型の2要素になる
    • int | NoneとOptional[int]のget_originの結果は、Python 3.13以前では異なり、3.14では同一になる
  • 型ヒントの値の型はAnyなので、型ヒントの値に対するメソッドの呼び出しや属性の参照は型チェッカーの確認の対象外になる

前提となる用語

型ヒントの評価

型ヒントの評価とは注釈に記述した式(intや"Item")から型のオブジェクトを取得する処理である。
Python 3.13以前では、通常の注釈はdefやclassの行の実行時に評価され、__annotations__に型のオブジェクトが格納される。
引用符の注釈とfrom __future__ import annotationsの注釈は評価されず、文字列のまま格納される。
評価の時点の詳細とPython 3.14の遅延評価は Pythonの型注釈の前方参照と3.14の注釈の遅延評価 で説明した。

ジェネリック型の外側の型と型引数

list[int]のlistを外側の型(origin)、intを型引数(argument)と呼ぶ。
dict[str, int]の外側の型はdictで、型引数はstrとintの2つである。

__annotations__の文字列は型として利用できない

以降の例の診断はmypy(--strict)とpyrightの標準の設定での出力で、実行結果はPython 3.13での出力である。

from __future__ import annotations
from typing import get_type_hints

def count(value: int) -> str:
    return str(value)

class Item:
    quantity: int

# future 指定では関数もクラスも文字列になる。
print(count.__annotations__)
print(Item.__annotations__)
print(get_type_hints(count))
print(get_type_hints(Item))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# {'value': 'int', 'return': 'str'}
# {'quantity': 'int'}
# {'value': <class 'int'>, 'return': <class 'str'>}
# {'quantity': <class 'int'>}

文字列の注釈はisinstanceで型として解釈されず、__annotations__の値を値の判定に利用すると実行時にTypeErrorになる。

from __future__ import annotations

class Item:
    quantity: int

# 注釈の文字列は isinstance の第2引数に渡せない。
print(isinstance(3, Item.__annotations__["quantity"]))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union

__annotations__の型はdict[str, Any]であるため、型チェッカーはこの誤りを指摘しない。
get_type_hints(Item)["quantity"]はintに評価されるため、同じ判定の出力はTrueになる。

from __future__ import annotations
from typing import get_type_hints

class Item:
    quantity: int

# get_type_hints で型へ解決してから検査する。
print(isinstance(3, get_type_hints(Item)["quantity"]))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# True

get_type_hintsの評価の規則

get_type_hints は、文字列の注釈を、関数やクラスの定義元のモジュールの名前空間(クラスでは、そのクラスの名前空間も)で評価する。

クラスに対してはメソッドの探索順序(__mro__)の順に基底クラスの注釈を統合し、派生クラスの注釈を優先する。

from typing import get_type_hints

class Base:
    identifier: int

class Item(Base):
    quantity: int

# 自身の注釈と、基底クラスを含む解決結果を比べる。
print(Item.__annotations__)
print(get_type_hints(Item))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# {'quantity': <class 'int'>}
# {'identifier': <class 'int'>, 'quantity': <class 'int'>}

Item.__annotations__にはクラスの本体の注釈だけが含まれ、基底クラスBaseのidentifierはget_type_hintsの結果にだけ含まれる。
基底クラスの注釈も一括で取得する場合は、__annotations__ではなくget_type_hintsの結果を利用する。

関数の中で定義したクラスを引用符の注釈で参照すると、モジュールの名前空間に名前がないのでNameErrorになる。

from typing import get_type_hints

def build() -> None:
    class Item:
        pass

    def accept(value: "Item") -> None:
        pass

    # 関数内の名前は既定の解決名前空間には入らない。
    print(get_type_hints(accept))

build()
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# NameError: name 'Item' is not defined. Did you mean: 'iter'?

引用符の注釈は文字列として保存され、定義した関数の中の名前空間は保存されないので、評価の時点で関数の中の名前を 参照できない 。
localnsに名前とクラスの辞書を指定すると、評価が成功する。

from typing import get_type_hints

def build() -> None:
    class Item:
        pass

    def accept(value: "Item") -> None:
        pass

    # localns にローカルクラスを渡して解決する。
    hints = get_type_hints(accept, localns={"Item": Item})
    print(hints["value"] is Item)

build()
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# True

型チェッカーは注釈を静的に解析するため、どちらのコードもエラーにしない。
NameErrorはget_type_hintsの呼び出しの時点まで発生しない。

get_originとget_argsで型を分解する

get_originの戻り値は外側の型、get_argsの戻り値は型引数のタプルである。

get_type_hintsはデフォルトでAnnotatedのメタデータを除去するので、メタデータも分解する場合はinclude_extras=Trueを指定する。
Annotatedのメタデータの取得は PythonのAnnotatedで型にメタデータを付加する で説明した。

typing.List[int]のようなtypingの別名の外側の型は、組み込みのlistに正規化される。

from typing import get_args, get_origin

# origin は外側の型、args は型引数を返す。
for hint in (list[int], dict[str, int], tuple[int, ...]):
    print(get_origin(hint), get_args(hint))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# <class 'list'> (<class 'int'>,)
# <class 'dict'> (<class 'str'>, <class 'int'>)
# <class 'tuple'> (<class 'int'>, Ellipsis)

tuple[int, ...]の型引数にはEllipsisが含まれるため、可変長のタプルの判定ではこの値を確認する。

from typing import Annotated, Callable, List, Literal, get_args, get_origin

# 特殊形式では origin と args の形も異なる。
for hint in (Literal["a", "b"], Callable[[int], str],
             List[int], Annotated[int, "m"], int):
    print(get_origin(hint), get_args(hint))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# typing.Literal ('a', 'b')
# <class 'collections.abc.Callable'> ([<class 'int'>], <class 'str'>)
# <class 'list'> (<class 'int'>,)
# typing.Annotated (<class 'int'>, 'm')
# None ()

型引数のないintに対しては、get_originの戻り値はNone、get_argsの戻り値は空のタプルである。

Python 3.13以前では、get_originの結果はint | Noneでtypes.UnionType、Optional[int]でtyping.Unionになる。

from typing import Optional, get_args, get_origin

# 2種類の union 記法を同じコードで比較する。
for hint in (int | None, Optional[int]):
    print(get_origin(hint), get_args(hint))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時(Python 3.13)
# <class 'types.UnionType'> (<class 'int'>, <class 'NoneType'>)
# typing.Union (<class 'int'>, <class 'NoneType'>)
# 実行時(Python 3.14)
# <class 'typing.Union'> (<class 'int'>, <class 'NoneType'>)
# <class 'typing.Union'> (<class 'int'>, <class 'NoneType'>)

|の構文は3.10で types.UnionType として追加され、typing.Unionとは別の型だった。
3.14で2つの型が 統一された ので、3.13以前も対象にする処理はtypes.UnionTypeとtyping.Unionの両方を判定する。

型ヒントの取得と分解による値の判定の実装例

次のvalidateは、dataclassのフィールドの型ヒントを取得し、辞書の値を判定してからインスタンスを生成する。
対象の型ヒントはint、str、list[int]、int | Noneの4種類だけで、デフォルト値のあるフィールドとfield(init=False)のフィールドは対象外である。

from dataclasses import dataclass, fields, is_dataclass
from types import UnionType
from typing import Any, Union, get_args, get_origin, get_type_hints

def matches(value: object, hint: Any) -> bool:
    # bool は int の部分型だが、この例では int として扱わない
    if hint in (int, str, type(None)):
        return type(value) is hint
    origin, args = get_origin(hint), get_args(hint)
    # list[int] は origin が list、args が (int,)
    if origin is list:
        return isinstance(value, list) and all(matches(x, args[0]) for x in value)
    # int | None は origin が UnionType(Optional[int] は Union)
    if origin in (UnionType, Union):
        return any(matches(value, member) for member in args)
    raise TypeError(f"unsupported hint: {hint}")

def validate[T](cls: type[T], data: dict[str, object]) -> T:
    if not is_dataclass(cls):
        raise TypeError("dataclass required")
    # フィールド名から型ヒントへの辞書を得る
    hints = get_type_hints(cls)
    for field in fields(cls):
        if not matches(data[field.name], hints[field.name]):
            raise TypeError(f"{field.name}: unexpected {type(data[field.name]).__name__}")
    return cls(**data)

@dataclass
class Item:
    quantity: int
    label: str
    scores: list[int]
    limit: int | None

print(validate(Item, {"quantity": 3, "label": "book", "scores": [1, 2], "limit": None}))
print(validate(Item, {"quantity": 3, "label": "book", "scores": [], "limit": 10}))
for name, value in (("quantity", "3"), ("label", 1), ("scores", [1, "2"]), ("limit", "10"), ("quantity", True)):
    data: dict[str, object] = {"quantity": 3, "label": "book", "scores": [1], "limit": None}
    data[name] = value
    try:
        validate(Item, data)
    except TypeError as error:
        print(error)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# Item(quantity=3, label='book', scores=[1, 2], limit=None)
# Item(quantity=3, label='book', scores=[], limit=10)
# quantity: unexpected str
# label: unexpected int
# scores: unexpected list
# limit: unexpected str
# quantity: unexpected bool

list[int]はisinstanceの第2引数に指定できないので、外側の型と型引数に分解してから要素ごとに判定する。
PEP 585 はisinstance([1, 2], list[str])の結果は要素の確認なしには判定できないので、型引数つきの型のisinstanceを禁止している。

from typing import get_type_hints

class Item:
    scores: list[int]

# 解決済みでも、型引数つき list は isinstance に渡せない。
hint = get_type_hints(Item)["scores"]
print(isinstance([1, 2], hint))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# TypeError: isinstance() argument 2 cannot be a parameterized generic

型ヒントの値はAnyで型チェッカーの確認の対象外になる

from typing import get_args, get_origin, get_type_hints, reveal_type

class Item:
    quantity: int

# 型チェッカーが見る API の戻り値を記録する。
reveal_type(get_type_hints(Item))
reveal_type(get_args(list[int]))
reveal_type(get_origin(list[int]))
# mypy
# Revealed type is "dict[str, Any]"
# Revealed type is "tuple[Any, ...]"
# Revealed type is "Any | None"
# pyright
# Type of "get_type_hints(Item)" is "dict[str, Any]"
# Type of "get_args(list[int])" is "tuple[Any, ...]"
# Type of "get_origin(list[int])" is "type"

型ヒントの値の型は静的に限定できないため、標準ライブラリの 型スタブ は辞書の値とタプルの要素の型をAnyにしている。
辞書とタプルの構造は確認の対象で、対象外は各要素の値の利用である。
get_originの結果の型はmypyではAny | Noneで、pyrightは引数のlist[int]からtypeと推論する。
そのためget_argsの結果に存在しないメソッドを呼び出しても、型チェッカーはエラーにしない。

from typing import get_args

# Any の要素には存在しないメソッド呼出しも型エラーにならない。
argument = get_args(list[int])[0]
argument.nonexistent_method()
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# AttributeError: type object 'int' has no attribute 'nonexistent_method'

型ヒントの値の扱いの誤りは実行時まで判明しないので、validateの例ではint、str、list[int]、int | Noneの型ヒントごとに、適合する値と適合しない値の両方で動作を確認する。

関連事例

  • データ分析支援

    事例:過去実績を提案に活用する分析の仕組み

    広告代理店との取り組みです。同社は過去実績の示唆を次の提案へ反映し、結果をどのように予測したか、その背景まで提案先のクライアントへ説明できるようになりました。KDOT は案ごとの見込みと判断材料を比較できる仕組みを業務アプリとして実装しました。さらに業務アプリの中核となる処理ロジックと機械学習モデルについて、特許手続きを担う弁理士が技術の新規性や工夫を検討するための資料を作成しました。その後この発明には特許が付与されました。

  • データ基盤構築 / 技術顧問(技術企業向け)

    事例:効果検証の分析処理基盤

    効果検証を提供する分析会社との取り組みです。同社は分析者の人数に比例してしか売上と利益を伸ばせない事業の形を、効果検証をプロダクトとして提供することで変革しようとしていました。手法とモデルは同社のまま、社内では開発できなかった、データと機械学習の重い推定を製品として動かす仕組みの開発を、開発支援会社の KDOT に任せました。推定を案件ごとの手作業ではなくシステムで実行できるようになったことで、同社は人数に比例しない形で売上と利益を伸ばすことを目指せるようになりました。

お問い合わせ・ご相談

システム開発、データ活用、プロダクトづくりのことならお気軽にご相談ください。要件が固まる前の整理や、お見積もりだけのご依頼も承ります。