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

## get_type_hints・get_origin・get_argsとは

`typing.get_type_hints`は、関数やクラスの型ヒントを実行時に取得する関数である。
文字列の注釈は型のオブジェクトに変換される。
`typing.get_origin`と`typing.get_args`は、`list[int]`を外側の型の`list`と型引数のタプル`(int,)`に分解する。
[`get_type_hints`](https://docs.python.org/3/library/typing.html#typing.get_type_hints) はPython 3.5から、[`get_origin`と`get_args`](https://docs.python.org/3/library/typing.html#typing.get_origin) は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の注釈の遅延評価](https://kdot.co.jp/kdotdev/python-forward-reference-annotations) で説明した。

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

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

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

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

```python
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`になる。

```python
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`になる。

```python
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`](https://docs.python.org/3/library/typing.html#typing.get_type_hints) は、文字列の注釈を、関数やクラスの定義元のモジュールの名前空間（クラスでは、そのクラスの名前空間も）で評価する。

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

```python
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`になる。

```python
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'?
```

引用符の注釈は文字列として保存され、定義した関数の中の名前空間は保存されないので、評価の時点で関数の中の名前を [参照できない](https://peps.python.org/pep-0563/#resolving-type-hints-at-runtime) 。
`localns`に名前とクラスの辞書を指定すると、評価が成功する。

```python
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で型にメタデータを付加する](https://kdot.co.jp/kdotdev/python-annotated-metadata) で説明した。

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

```python
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`が含まれるため、可変長のタプルの判定ではこの値を確認する。

```python
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`になる。

```python
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`](https://peps.python.org/pep-0604/) として追加され、`typing.Union`とは別の型だった。
3.14で2つの型が [統一された](https://docs.python.org/3/whatsnew/3.14.html#typing) ので、3.13以前も対象にする処理は`types.UnionType`と`typing.Union`の両方を判定する。

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

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

```python
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](https://peps.python.org/pep-0585/#parameters-to-generics-are-available-at-runtime) は`isinstance([1, 2], list[str])`の結果は要素の確認なしには判定できないので、型引数つきの型の`isinstance`を禁止している。

```python
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で型チェッカーの確認の対象外になる


```python
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"
```

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

```python
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`の型ヒントごとに、適合する値と適合しない値の両方で動作を確認する。
