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

Union型とは
PythonのUnion型とは、値が複数の型のうちのいずれかであることの型での表現である。
int | str型の変数にはintの値とstrの値のどちらも代入でき、Union[int, str]と同一の型である。
X | Yの表記はPython 3.10で 追加された 構文で、それ以前は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の部分型である。
型の仕様 はUnion型を、各要素の型の値の集合の和集合と定義し、要素の型はすべてUnion型の部分型になる。
型の絞り込み
型の絞り込み(type narrowing)とは、if文などの条件をもとに、型チェッカーが分岐の中での変数の型の範囲を宣言より限定する処理である。
int | str型のvalueは、if isinstance(value, str):の分岐の中ではstr型と判定される。
Noneの確認による絞り込みは PythonのOptionalとNoneチェック で説明した。
引数の型がobjectなら値の操作がエラーになる
以降の例のnormalizeは、文字列を大文字の文字列に、整数を1の加算の結果の文字列に変換する関数である。
例のtyping.assert_typeはPython 3.11以降の関数で、診断はmypyとpyrightの標準の設定での出力である。
どの型の値も引数にできる関数の型はobjectである。
しかしobject型の値に対しては、objectに定義された操作しか型チェッカーが許可しない。
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()の、確認なしの呼び出しがエラーになる。
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を前提にした演算はエラーになる。
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の型の絞り込みを行う。
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になる。
要素以外の型の値を引数にした呼び出しは、型チェッカーがエラーにする。
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の引数に指定できない。
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 が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]と等しい。
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]に展開される。
型の仕様 は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]の表記を使用する。
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以降しか指定できず 、このエラーを検出できない。
isinstanceの第2引数に型引数付きの型は指定できない
isinstanceは実行時の値のクラスを確認する関数で、list[int]の要素の型は判定できない。
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 はlist[str]をlistとして判定する案を不採用にした。
要素の型の確認と誤解されやすいのに、isinstance([1, 2, 3], list[str])がTrueになるからである。
要素まで実行時に確認する案も、コレクションの走査が必要で、一部のコレクションでは中身を消費するので不採用になった。
したがってisinstance(value, list)でlistかを確認し、要素の型は別に確認する。
要素の型の確認の結果を型チェッカーに通知するには、自作の関数の戻り値の型にTypeGuardやTypeIsを指定する。
同じ型の値を異なる意味で区別できない
int | strの値の種類は、値そのもののクラスで区別できる。
Haskell や Rust の直和型では、値の種類を識別する印(タグ)として構築子が値の一部になるが、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と同一の型になる。
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の分岐の対象になる。
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はクラスの継承関係で判定する点が異なる。


