# PythonのUnion型とisinstanceによる型の絞り込み

## Union型とは

PythonのUnion型とは、値が複数の型のうちのいずれかであることの型での表現である。
`int | str`型の変数には`int`の値と`str`の値のどちらも代入でき、`Union[int, str]`と同一の型である。
`X | Y`の表記はPython 3.10で [追加された](https://peps.python.org/pep-0604/) 構文で、それ以前は`typing.Union`を利用する。

- 引数の型が`object`の関数では、どの型の値も引数にできるが、型チェッカーは`object`に定義された操作しか許可しない
- 引数の型をUnion型にすると、型チェッカーは要素の型以外の値を引数にした呼び出しをエラーにする
  - 確認なしで利用できる操作は、全要素の型に共通の操作だけである
  - 想定外の`float`の値を引数にした呼び出しも、実行前に発見できる
- `isinstance`で値の型を確認すると、型チェッカーが分岐ごとに変数の型を限定し、その型の操作を許可する
- 同じ型の値を別の意味の要素として列挙しても、Union型では区別できず、`int | int`は`int`と同一の型になる
- `bool`は`int`のサブクラスで、`isinstance(value, int)`は`True`でも成立する
- `isinstance`の第2引数への型引数付きの指定（`list[int]`など）は、実行時に`TypeError`になる

## 前提となる用語

### 部分型

型Aの値を型Bの値の代わりに利用できるとき、AをBの部分型と呼ぶ。
`int`は`int | str`の部分型で、`int | str`は`int | str | None`の部分型である。
[型の仕様](https://typing.python.org/en/latest/spec/concepts.html#union-types) はUnion型を、各要素の型の値の集合の和集合と定義し、要素の型はすべてUnion型の部分型になる。

### 型の絞り込み

型の絞り込み（type narrowing）とは、`if`文などの条件をもとに、型チェッカーが分岐の中での変数の型の範囲を宣言より限定する処理である。
`int | str`型の`value`は、`if isinstance(value, str):`の分岐の中では`str`型と判定される。
`None`の確認による絞り込みは [PythonのOptionalとNoneチェック](https://kdot.co.jp/kdotdev/python-optional-none) で説明した。

## 引数の型がobjectなら値の操作がエラーになる

以降の例の`normalize`は、文字列を大文字の文字列に、整数を1の加算の結果の文字列に変換する関数である。
例の`typing.assert_type`はPython 3.11以降の関数で、診断はmypyとpyrightの標準の設定での出力である。

どの型の値も引数にできる関数の型は`object`である。
しかし`object`型の値に対しては、`object`に定義された操作しか型チェッカーが許可しない。

```python
def normalize(value: object) -> str:
    if isinstance(value, str):
        return value.upper()
    return str(value + 1)
# mypy
# error: Unsupported operand types for + ("object" and "int")  [operator]
# pyright
# error: Operator "+" not supported for types "object" and "Literal[1]" (reportOperatorIssue)
```

`isinstance`で`str`を確認した後の`else`の側でも、`value`の型は`object`のままで、`+ 1`がエラーになる。
引数の想定が`int`と`str`の2種類だけなら、その2つを要素にしたUnion型で引数の型を表現できる。

## Union型の値は全要素の型に共通の属性だけを利用できる

引数の型を`int | str`にすると、型チェッカーは`value`が`int`の場合と`str`の場合の両方を前提に判定する。
次の説明用の関数`shout`では、`str`のメソッドで`int`には存在しない`upper()`の、確認なしの呼び出しがエラーになる。

```python
def shout(value: int | str) -> str:
    return value.upper()
# mypy
# error: Item "int" of "int | str" has no attribute "upper"  [union-attr]
# pyright
# error: Cannot access attribute "upper" for class "int"
#   Attribute "upper" is unknown (reportAttributeAccessIssue)
# 実行時（shout(1)）
# AttributeError: 'int' object has no attribute 'upper'
```

戻り値の型がUnion型の関数でも、呼び出し側の操作は全要素の型に共通の操作に限られる。
次の`parse`の戻り値は`int`か`str`なので、`int`を前提にした演算はエラーになる。

```python
def parse(text: str) -> int | str:
    return int(text) if text.isdigit() else text

print(parse("1") + 1)
# mypy
# error: Unsupported operand types for + ("str" and "int")  [operator]
# pyright
# error: Operator "+" not supported for types "int | str" and "Literal[1]"
#   Operator "+" not supported for types "str" and "Literal[1]" when expected type is "object" (reportOperatorIssue)
```

実行時の結果は`2`だが、`parse("a")`なら`TypeError`になるので、型チェッカーは呼び出し側に型の確認を要求する。
`print(parse("1"))`のように全要素の型に共通の操作なら、確認なしでもエラーにならない。

## isinstanceで型を確認すると分岐ごとに変数の型が限定される

`isinstance`による確認の後では、型チェッカーが分岐ごとに`value`の型の絞り込みを行う。

```python
from typing import assert_type

def normalize(value: int | str) -> str:
    if isinstance(value, str):
        assert_type(value, str)
        return value.upper()
    assert_type(value, int)
    return str(value + 1)

print(normalize("a"), normalize(1))  # A 2
```

`assert_type`は、型チェッカーの判定の結果と第2引数の型の不一致をエラーにする関数で、実行時には何もしない。
`if`の分岐の中では`str`型、`return`の後では残りの`int`型と判定され、どちらの型のメソッドもエラーにならない。
引数の型が`object`の場合と異なり、`if`の分岐の後の判定は、確認済みの`str`を要素から除外した`int`になる。

要素以外の型の値を引数にした呼び出しは、型チェッカーがエラーにする。

```python
print(normalize(1.5))
print(normalize(b"x"))
# mypy
# error: Argument 1 to "normalize" has incompatible type "float"; expected "int | str"  [arg-type]
# error: Argument 1 to "normalize" has incompatible type "bytes"; expected "int | str"  [arg-type]
# pyright
# error: Argument of type "float" cannot be assigned to parameter "value" of type "int | str" in function "normalize"
# error: Argument of type "Literal[b"x"]" cannot be assigned to parameter "value" of type "int | str" in function "normalize"
```

実行時には`normalize(1.5)`は`"2.5"`になり、例外は発生しない。
`str`以外の値はすべて`int`の側の処理になるので、型チェッカーがなければこの誤りは実行の結果からも発見しにくい。
`normalize(b"x")`は実行時に`TypeError`で失敗するが、型チェッカーなら呼び出しの行で発見できる。

Union型どうしの代入は、代入元の各要素の型が代入先のどれかの要素の型の部分型なら可能である。
`bool | str`型の値は、`bool`が`int`の部分型なので`int | str`型の引数にできる。
次の説明用の関数では要素の多い`accept_wide`の引数には指定でき、`bytes`を含む値は`accept_narrow`の引数に指定できない。

```python
def accept_wide(x: int | str | None) -> None: ...
def accept_narrow(x: int | str) -> None: ...

def example(v: int | str, w: int | str | bytes) -> None:
    accept_wide(v)    # ok
    accept_narrow(w)
# mypy
# error: Argument 1 to "accept_narrow" has incompatible type "int | str | bytes"; expected "int | str"  [arg-type]
```

## X | Yの構文とtyping.Unionの違い

[PEP 604](https://peps.python.org/pep-0604/) がPython 3.10で`X | Y`の構文を追加し、型の注釈と`isinstance`の第2引数で利用可能にした。
PEP 604の動機は`typing`の`import`と角括弧の記述が必要な`Union[X, Y]`より短い表記の導入である。
### int | strとUnion[int, str]の等価性

`int | str`は実行時の値としても`typing.Union[int, str]`と等しい。

```python
from typing import Union

print(Union[int, str] == (int | str))     # True
print(isinstance(1, int | str))           # True
print(isinstance(1, (int, str)))          # True
print(Union[str, int] == Union[int, str])  # True
print(Union[int, Union[str, bytes]] == Union[int, str, bytes])  # True
```

`Union[str, int]`と`Union[int, str]`は等しく、入れ子の`Union[int, Union[str, bytes]]`は`Union[int, str, bytes]`に展開される。

[型の仕様](https://typing.python.org/en/latest/spec/historical.html#union-and-optional) は`Union`を、`|`の構文の追加以前からの表記として「Historical and deprecated features」の章に分類している。

### Python 3.9以前での制約

Python 3.7から3.9でも、`from __future__ import annotations`の指定があれば、型の注釈の中の`int | str`はエラーにならない。
この指定で注釈は実行時に評価されず、文字列のまま保持されるからである。
ただし`typing.get_type_hints`のように注釈を実行時に評価する処理や、型の注釈の外の`int | str`は、Python 3.9以前では`TypeError`になる。
その場合は`Union[int, str]`の表記を使用する。

```python
from __future__ import annotations

def f(x: int | str) -> None: ...  # ok

IntOrStr = int | str
def g(x: object) -> bool:
    return isinstance(x, int | str)
# pyright（Python 3.9を解析対象にした場合）
# error: Alternative syntax for unions requires Python 3.10 or newer (reportGeneralTypeIssues)
# error: Alternative syntax for unions requires Python 3.10 or newer (reportGeneralTypeIssues)
```

pyrightは解析対象のバージョンを`--pythonversion 3.9`のように指定すると、型の注釈の外の2か所をエラーにする。
[mypyは2.4の時点で解析対象にPython 3.10以降しか指定できず](https://github.com/python/mypy/blob/v2.4.1/mypy/defaults.py) 、このエラーを検出できない。

## isinstanceの第2引数に型引数付きの型は指定できない

`isinstance`は実行時の値のクラスを確認する関数で、`list[int]`の要素の型は判定できない。

```python
def is_int_list(value: object) -> bool:
    return isinstance(value, list[int])
# mypy
# error: Parameterized generics cannot be used with class or instance checks  [misc]
# pyright
# error: Second argument to "isinstance" must be a class or tuple of classes
# 実行時
# TypeError: isinstance() argument 2 cannot be a parameterized generic
```

[PEP 585](https://peps.python.org/pep-0585/#making-isinstance-obj-list-str-perform-a-check-ignoring-generics) は`list[str]`を`list`として判定する案を不採用にした。
要素の型の確認と誤解されやすいのに、`isinstance([1, 2, 3], list[str])`が`True`になるからである。
要素まで実行時に確認する案も、コレクションの走査が必要で、一部のコレクションでは中身を消費するので不採用になった。
したがって`isinstance(value, list)`で`list`かを確認し、要素の型は別に確認する。
要素の型の確認の結果を型チェッカーに通知するには、自作の関数の戻り値の型に`TypeGuard`や`TypeIs`を指定する。

## 同じ型の値を異なる意味で区別できない

`int | str`の値の種類は、値そのもののクラスで区別できる。
[Haskell](https://hackage.haskell.org/package/base/docs/Data-Either.html) や [Rust](https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html) の直和型では、値の種類を識別する印（タグ）として構築子が値の一部になるが、PythonのUnion型の値にはタグがない。

| 言語 | 型 | 値の種類の区別 | 同じ要素の重複 |
|---|---|---|---|
| Python | `int \| str` | 値のクラス（`isinstance`） | `int \| int`は`int`と同一 |
| TypeScript | `number \| string` | 値の型（`typeof`） | `number \| number`は`number`と同一 |
| Haskell | `Either Int String` | 構築子（`Left`か`Right`） | `Either Int Int`は`Int`と別の型 |
| Rust | `enum`（`A(i32)`、`B(String)`） | 構築子 | 構築子が異なれば区別できる |

Union型は要素の型の値の集合の和集合で、タグがないので、`int | int`と`Union[int, int]`は`int`と同一の型になる。

```python
from typing import Union, assert_type

def f(x: int | int) -> None:
    assert_type(x, int)  # ok

def g(x: Union[int, int]) -> None:
    assert_type(x, int)  # ok
# mypy: Success: no issues found in 1 source file
# pyright: 0 errors, 0 warnings, 0 informations
```

mypyとpyrightはこの重複に対してエラーと警告のどちらも出力しない。
1つの型の値を2つの意味で区別する必要がある場合は、Union型ではなく、意味ごとにクラスを定義して列挙する。

`True`は`int`の分岐の対象になる。

```python
def kind(value: int | str) -> str:
    if isinstance(value, int):
        return "int"
    return "str"

print(kind(True))  # int
```

`kind(True)`はmypyとpyrightのどちらでも型エラーにならない。
`bool`を別に処理するなら、`isinstance(value, bool)`の確認を`int`の確認より先に記述する。

TypeScriptのUnion型もタグのない合併だが、`typeof`の確認は値の型で行い、Pythonの`isinstance`はクラスの継承関係で判定する点が異なる。
