# PythonのTypeGuardとTypeIsによる型の絞り込み

## TypeGuardとTypeIsとは

`TypeGuard`と`TypeIs`とは、自作の判定関数の戻り値の型の注釈である。
この注釈で、関数の結果が引数の型の絞り込みの条件になる。
実行時の戻り値は普通の`bool`の値で、効果は型チェッカーの判定に限られる。
`TypeGuard`はPython 3.10、`TypeIs`はPython 3.13で [`typing`に追加された](https://typing.python.org/en/latest/guides/type_narrowing.html#how-to-use-typeis-and-typeguard) 。
それ以前のPythonでは`typing_extensions`（`TypeIs`は4.10.0以降）から利用する。

- 戻り値の型が`bool`の自作の判定関数では、中で`isinstance`を実行していても、型チェッカーは`if`の分岐の中で引数の型を限定しない
- 説明用の判定関数`is_str`の戻り値の型を`TypeGuard[str]`か`TypeIs[str]`にすると、`if is_str(value):`の分岐の中では`str`のメソッドの呼び出しがエラーにならない
- `TypeGuard`の絞り込みは`True`の分岐だけで、`TypeIs`は`True`と`False`の両方の分岐で型を限定する
  - `int | str`型の値の`TypeIs[str]`の`else`の分岐は`int`になり、`TypeGuard[str]`では`int | str`のままである
  - 引数の型が`list[object]`の関数の`TypeIs[list[str]]`のように、引数の型の部分型でない型への絞り込みは`TypeIs`では不可能で、`TypeGuard`だけで可能である
- 判定の条件と戻り値の型の約束の一致は型チェッカーの確認の対象外で、条件に誤りがあれば絞り込みの判定も不正確になる

## 前提となる用語

### 型の絞り込み

型の絞り込み（type narrowing）とは、型チェッカーが条件の判定をもとに、分岐の中の変数の型を型注釈の型（declared type）より限定する処理である。
`int | str`型の`value`は、`if isinstance(value, str):`の分岐の中では`str`型と判定される。
条件として解釈される式の種類と、絞り込みの対象外になる書き方は [Pythonの型チェッカーによる型の絞り込みの仕組み](https://kdot.co.jp/kdotdev/python-type-narrowing) で説明した。

### 部分型

型Aの値を型Bの値の代わりに利用可能なとき、AをBの部分型と呼ぶ。
`str`は`object`の部分型で、`bool`は`int`の部分型である。
`list[object]`型の値には`int`の要素を追加できるが、`list[str]`型の値には追加できないので、`list[str]`は`list[object]`の部分型ではない。

## 戻り値の型がboolの関数では型が限定されない

以降の例の型チェッカーの診断はmypyとpyrightの標準の設定での出力である。

例の [`typing.assert_type`](https://docs.python.org/3/library/typing.html#typing.assert_type) はPython 3.11以降の関数である。
`assert_type`は、型チェッカーの判定の結果が第2引数の型と異なる場合をエラーにする関数で、実行時には何もしない。

確認の処理を自作の関数の中に記述すると、その関数の呼び出しは型チェッカーにとって絞り込みの条件ではない。

```python
def is_str(value: object) -> bool:
    return isinstance(value, str)

def show(value: int | str) -> None:
    if is_str(value):
        print(value.upper())
# mypy
# error: Item "int" of "int | str" has no attribute "upper"  [union-attr]
# pyright
# error: Cannot access attribute "upper" for class "int"
# 実行時（show("hello")）
# HELLO
```

`isinstance`を`if`文の条件に直接記述すれば絞り込みの対象になるが、要素の型の確認のような複数の行の処理は、関数にしないと呼び出し側ごとに重複する。

## TypeGuardで関数の結果を絞り込みに反映する

戻り値の型を`TypeGuard[T]`にすると、型チェッカーは関数の結果が`True`の分岐で、1番目の引数の式を`T`型と判定する。
次の説明用の関数`is_str_list`の戻り値は、要素がすべて`str`の場合に`True`である。

```python
from typing import TypeGuard, assert_type

def is_str_list(values: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(value, str) for value in values)

def show(items: list[object]) -> None:
    if is_str_list(items):
        assert_type(items, list[str])
        print(", ".join(items))
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
```

`isinstance(items, list[str])`は [実行時の`TypeError`](https://peps.python.org/pep-0585/#parameters-to-generics) になる。
各要素の確認を関数として定義する場合は、戻り値の型に`TypeGuard[list[str]]`を指定できる。
`TypeGuard`では、このように引数の型の部分型でない型への絞り込みも [許可されている](https://peps.python.org/pep-0647/#enforcing-strict-narrowing) 。
引数の型の部分型への限定を必須にすると、`list[object]`から`list[str]`への絞り込みのような有用な例が不可能になるからである。
ただし、同じリストを`list[object]`として保持する別の変数から`str`以外の要素を追加すると、`list[str]`という絞り込みの前提が成立しなくなる。

### Falseの分岐では型が限定されない

`TypeGuard`による絞り込みは、関数の結果が`True`の分岐に限られる。

```python
from typing import TypeGuard, assert_type

def is_str(value: object) -> TypeGuard[str]:
    return isinstance(value, str)

def show(value: int | str) -> None:
    if is_str(value):
        assert_type(value, str)
    else:
        assert_type(value, int | str)
        print(value + 1)
# mypy
# error: Unsupported operand types for + ("str" and "int")  [operator]
# pyright
# error: Operator "+" not supported for types "int | str" and "Literal[1]"
```

`else`の分岐の`value`は`int | str`のままで、`value + 1`がエラーになる。
`TypeGuard[T]`の`False`は「`T`型でない」という意味ではないので、`False`の分岐から`T`を除外できない。
[PEP 742](https://peps.python.org/pep-0742/#typeis-and-typeguard) は正の整数の場合だけ`True`の`TypeGuard[int]`も適切な用途の例としており、その`False`の分岐には負の整数も到達する。

## TypeIsはFalseの分岐でも型を限定する

この関数の戻り値の型を`TypeIs[str]`にすると、`else`の分岐の`value`は`str`を除外した`int`になる。

```python
from typing import TypeIs, assert_type

def is_str(value: object) -> TypeIs[str]:
    return isinstance(value, str)

def show(value: int | str) -> None:
    if is_str(value):
        assert_type(value, str)
    else:
        assert_type(value, int)
        print(value + 1)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
```

`TypeIs[T]`の関数の戻り値は、引数が`T`型の場合に`True`、それ以外の場合に`False`という前提である。
この前提があるので、型チェッカーは`False`の分岐でも`isinstance`の規則で`T`を除外できる。

`TypeGuard[T]`の`True`の分岐の型は`T`そのものだが、`TypeIs[T]`の`True`の分岐では、引数の元の型と`T`の両方に属する値の型に限定される。

```python
from typing import TypeGuard, TypeIs, assert_type

def is_int_guard(value: object) -> TypeGuard[int]:
    return isinstance(value, int)

def is_int(value: object) -> TypeIs[int]:
    return isinstance(value, int)

def show(value: bool | str) -> None:
    if is_int_guard(value):
        assert_type(value, int)

def show_intersection(value: bool | str) -> None:
    if is_int(value):
        assert_type(value, bool)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
```

`bool | str`型の値の`TypeGuard[int]`の`True`の分岐は`int`で、元の型の`bool`の情報は判定に反映されない。
元の型を条件付きで保持する案は、Union型などでの規則の複雑化に対して利点が限定的として [不採用になった](https://peps.python.org/pep-0647/#conditionally-applying-typeguard-type) 。
`TypeIs[int]`の`True`の分岐は、`bool | str`の要素のうち`int`の部分型の`bool`である。

### TypeIsの型引数は引数の型の部分型に限られる

`TypeIs`の型引数が引数の型の部分型でない場合、関数の定義の行がエラーになる。

```python
from typing import TypeIs

def is_str_list(values: list[object]) -> TypeIs[list[str]]:
    return all(isinstance(value, str) for value in values)
# mypy
# error: Narrowed type "list[str]" is not a subtype of input type "list[object]"  [narrowed-type-not-subtype]
# pyright
# error: Return type of TypeIs ("list[str]") is not consistent with value parameter type ("list[object]") (reportGeneralTypeIssues)
```

引数の型を`list[object]`のまま要素の型を確認するこの例では、`TypeGuard`を使用する。
要素の参照のための関数では、引数の型を`Sequence[object]`に変更できる。
`Sequence[str]`はその部分型なので、`TypeIs[Sequence[str]]`を指定できる。
`Sequence`は要素の追加のメソッドのない読み取り専用の型なので、`list`と異なり、要素の型の部分型の関係がそのまま`Sequence`の部分型の関係になる。
この性質を [共変](https://typing.python.org/en/latest/reference/generics.html#variance-of-generic-types) と呼ぶ。

## 関数の実装と戻り値の型の不一致は検出されない

`TypeGuard`と`TypeIs`の関数の中の処理と戻り値の型の意味の一致は、型チェッカーの確認の対象外である。
次の`is_nonempty_str`の戻り値は空文字列の場合に`False`で、`TypeIs[str]`の前提に反する。

```python
from typing import TypeIs, assert_type

def is_nonempty_str(value: object) -> TypeIs[str]:
    return isinstance(value, str) and value != ""

def read_value() -> int | str:
    return ""

value = read_value()
if is_nonempty_str(value):
    assert_type(value, str)
else:
    assert_type(value, int)
    print(value + 1)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時
# TypeError: can only concatenate str (not "int") to str
```

型チェッカーは`else`の分岐の`value`を`int`と判定するが、実行時の値は空文字列で、`value + 1`が`TypeError`で失敗する。
空文字列以外の`str`だけを`True`にする条件なら、`False`の分岐を限定しない`TypeGuard[str]`が適切な指定である。
[typingの解説の文書](https://typing.python.org/en/latest/guides/type_narrowing.html#incorrect-typeis-and-typeguard-functions) も、条件と戻り値の型の約束が一致しない関数を型チェッカーは検出できないと説明している。
`TypeIs[T]`の関数の条件は、`T`型の値すべてで`True`、それ以外の値で`False`になる条件にし、テストで`True`と`False`の両方の値を確認する。

## 絞り込みの対象は1番目の引数である

絞り込みの対象は関数の1番目の位置引数の式である。
メソッドでは`self`の次の引数が対象になり、引数のない関数への指定はエラーになる。

```python
from typing import TypeGuard, TypeIs, assert_type

def f() -> TypeGuard[int]:
    return True

class StringChecker:
    def is_str(self, value: object) -> TypeIs[str]:
        return isinstance(value, str)

def show(value: int | str) -> None:
    checker = StringChecker()
    if checker.is_str(value):
        assert_type(value, str)
# mypy
# error: TypeGuard functions must have a positional argument  [valid-type]
# pyright
# error: User-defined type guard functions and methods must have at least one input parameter (reportGeneralTypeIssues)
```

任意の引数を絞り込みの対象とする案は [不採用になった](https://peps.python.org/pep-0647/#narrowing-of-arbitrary-parameters) 。
TypeScriptの開発者も、1番目以外の引数を対象にする実例を認識していなかったからである。
`self`を対象にする案も、実装が複雑になる割に用途が少ないとして不採用になった。

## TypeGuardとTypeIsの使い分け

[PEP 742](https://peps.python.org/pep-0742/#rationale) は多くの場合に`TypeIs`の動作のほうが利用者の期待と一致するとして、まず`TypeIs`の検討を推奨している。
`TypeGuard`は非推奨ではなく、次の2つの場合は`TypeIs`ではなく`TypeGuard`で表現する。

| 条件 | 指定 |
|---|---|
| 引数の型の部分型への限定で、`T`型の値すべてで`True` | `TypeIs[T]` |
| 引数の型の部分型でない型への限定（`list[object]`から`list[str]`など） | `TypeGuard[T]` |
| `T`型の値の一部だけで`True`（正の整数だけなど） | `TypeGuard[T]` |

`TypeGuard`の型引数が引数の型と互換なときだけ`TypeIs`と同じ動作にする案は、[PEP 742で不採用になった](https://peps.python.org/pep-0742/#change-the-behavior-of-typeguard) 。
既存の`TypeGuard`の関数の`else`の分岐の判定に影響が及び、型引数による動作の切り替えも利用者の混乱の原因になるからである。

TypeScriptの [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)（`x is T`）は、`TypeIs`と同様に`false`の分岐でも型を限定する。
`TypeGuard`は、成立時に限って型の情報を付与するTyped Racketの [one-sided propositions](https://docs.racket-lang.org/ts-guide/occurrence-typing.html#%28part._.One-sided_.Propositions%29) に近い。
