Pythonのmatch文とUnion型で代数的データ型の網羅性を確認する

代数的データ型とは
代数的データ型(algebraic data type)とは、値が複数のバリアント(variant)のどれか1つで(例: 図形が円か長方形のどちらか)、フィールドの構成がバリアントごとに異なる種類の型である。
Pythonでは、バリアントごとのクラスをdataclassで定義し、それらのUnion型を型エイリアスにすることで表現できる。
値のバリアントによる分岐はmatch文のクラスパターンで記述し、全部のバリアントの処理の有無を型チェッカーが確認する。
- 引数の型がバリアントの共通の基底クラスの関数では、全部のバリアントの
caseを記述しても、型チェッカーは網羅を判定しない- 基底クラスの型の値には、未知のサブクラスのインスタンスも含まれる
- 実行時のmatch文は一致する
caseがなければ何も実行せず、戻り値の型がfloatの関数でもNoneが戻り値になる
- バリアントのUnion型を引数の型にすると、バリアントの追加時に処理の不足した関数を型エラーにできる
- 戻り値の型が
Noneを含まない関数では、関数の末尾への到達がエラーになる - 末尾の
case _:のassert_never(引数に処理していない型の値があると型エラーにする関数)の場合、戻り値の型と無関係に、未処理のバリアントのクラス名がエラー文に表示される - Union型の
isinstanceの分岐でも同じエラーになり、match文ではクラスの判定とフィールドの値の代入を1つのcaseに記述できる
- 戻り値の型が
- ガード(
case ... if 条件)付きのcaseのクラスは、型チェッカーの判定で処理済みにならない - 判別用のキーのあるTypedDict(キーごとに値の型を指定した辞書の型)のUnion型では、マッピングパターンでの分岐の判定がmypyとpyrightで異なる
バリアントのクラスとUnion型で図形を定義する
以降の例の診断は、mypy(--strict)とpyrightの標準の設定での出力である。
match文はPython 3.10以降、assert_neverは3.11以降の機能で、3.10ではassert_neverをtyping_extensionsから利用する。
次のCircleとRectは説明用の図形のクラスで、Shapeはその2つのUnion型である。
areaは図形の面積を計算する説明用の関数である。
from dataclasses import dataclass
@dataclass(frozen=True)
class Circle:
radius: float
@dataclass(frozen=True)
class Rect:
width: float
height: float
Shape = Circle | Rect
def area(shape: Shape) -> float:
match shape:
case Circle(radius=r):
return 3.14159 * r * r
case Rect(width=w, height=h):
return w * h
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
case Circle(radius=r):は PEP 634 のクラスパターンで、値がCircleのインスタンスの場合に一致し、radius属性の値をrに代入する。
型チェッカーはcase Circle(...)の分岐のshapeをCircle型、rをfloat型と判定する。
この条件の分岐による型の限定を、型の絞り込み(type narrowing) と呼ぶ。
クラスパターンの位置引数(case Rect(w, h):)も使用できる。
dataclassesのドキュメント の規定では、dataclassはkeyword-onlyでないフィールドの定義順の名前を__match_args__に設定する。
areaの末尾にはreturnが無いが、エラーにはならない。
2つのcaseでShapeの全部のバリアントを処理したので、型チェッカーはmatchの後の関数の末尾を到達不能と判定する。
バリアントの追加で処理の不足が型エラーになる
Shapeへの三角形のTriangleの追加後、areaが変更前のままなら、areaの定義がエラーになる。
@dataclass(frozen=True)
class Triangle:
base: float
height: float
Shape = Circle | Rect | Triangle
def area(shape: Shape) -> float:
match shape:
case Circle(radius=r):
return 3.14159 * r * r
case Rect(width=w, height=h):
return w * h
# mypy
# error: Missing return statement [return]
# pyright
# error: Function with declared return type "float" must return value on all code paths
# "None" is not assignable to "float" (reportReturnType)
matchの後にTriangleの値の可能性があるので、関数の末尾に到達し、戻り値がNoneになる経路が存在する。
このエラーは関数の末尾に到達する経路があることを示し、エラー文に未処理のバリアントのTriangleは表示されない。
assert_neverで未処理のバリアントを表示する
末尾のcase _:での assert_never の呼び出しでは、未処理のバリアントのクラス名がエラー文に表示される。
次の例はCircleとRectのShapeで、Rectのcaseが無い。
from dataclasses import dataclass
from typing import assert_never
@dataclass(frozen=True)
class Circle:
radius: float
@dataclass(frozen=True)
class Rect:
width: float
height: float
Shape = Circle | Rect
def area(shape: Shape) -> float:
match shape:
case Circle(radius=r):
return 3.14159 * r * r
case _:
assert_never(shape)
# mypy
# error: Argument 1 to "assert_never" has incompatible type "Rect"; expected "Never" [arg-type]
# pyright
# error: Argument of type "Rect" cannot be assigned to parameter "arg" of type "Never" in function "assert_never"
# Type "Rect" is not assignable to type "Never" (reportArgumentType)
case _:の分岐のshapeは、処理済みのCircleを除いたRect型である。
assert_neverの引数の型は値の集合が空のNeverで、未処理のバリアントがあるとエラーになる。
戻り値の型がNoneの関数では、標準の設定の場合、caseの不足はassert_neverが無ければ型エラーにならない。
assert_neverの仕組みと、assert_neverなしで型チェッカーにmatch文の網羅性を確認させるための設定は Neverとassert_neverの記事 で説明した。
Union型とisinstanceの記事 で説明したとおり、Union型の値のisinstanceの分岐でも型は限定され、未処理のバリアントは同じエラーになる。
def area(shape: Shape) -> float:
if isinstance(shape, Circle):
return 3.14159 * shape.radius * shape.radius
else:
assert_never(shape)
# mypy
# error: Argument 1 to "assert_never" has incompatible type "Rect"; expected "Never" [arg-type]
# pyright
# error: Argument of type "Rect" cannot be assigned to parameter "arg" of type "Never" in function "assert_never"
assert_neverによる網羅性の確認は、match文に固有の機能ではなく、Union型の絞り込みの結果である。
match文の利点は、クラスの判定とフィールドの値の代入を1つのcaseに記述できることである。
共通の基底クラスを引数の型にすると網羅性を判定できない
網羅性の判定には、バリアントの集合が型として確定している必要がある。
次の例では、CircleとRectを共通の基底クラスShapeのサブクラスにすると、全部のcaseの記述後もassert_neverがエラーになる。
class Shape:
pass
@dataclass(frozen=True)
class Circle(Shape):
radius: float
@dataclass(frozen=True)
class Rect(Shape):
width: float
height: float
def area(shape: Shape) -> float:
match shape:
case Circle(radius=r):
return 3.14159 * r * r
case Rect(width=w, height=h):
return w * h
case _:
assert_never(shape)
# mypy
# error: Argument 1 to "assert_never" has incompatible type "Shape"; expected "Never" [arg-type]
# pyright
# error: Argument of type "Shape" cannot be assigned to parameter "arg" of type "Never" in function "assert_never"
# Type "Shape" is not assignable to type "Never" (reportArgumentType)
CircleとRectのcaseの記述後も、case _:のshapeはShape型と判定される。
Shape型の値には、Shapeそのもののインスタンスや、別のモジュールで定義されるサブクラスのインスタンスも含まれるからである。
CircleとRectのUnion型(Circle | Rect)が引数の型の関数はエラーにならない。
match文を提案した PEP 622 は、サブクラスの定義を同じモジュールに限定する@sealedデコレータを、型チェッカーの網羅性の確認のために提案した。
PEP 622はこの節で、Union型の定義に未追加のクラスは網羅性の確認の対象外になる欠点を指摘している。
@sealedはPEP 634で採用されたmatch文の仕様には含まれていない。
| 言語 | 確定したバリアントの集合の記述 |
|---|---|
| Haskell | data Shape = Circle Double | Rect Double Double |
| Scala | sealed trait Shapeと、同じファイルのcase class |
| TypeScript | 判別用のプロパティ付きのオブジェクト型のUnion型 |
| Python | dataclassのクラスのUnion型 |
Union型に追加し忘れたクラス
Union型に未追加のクラスの値は、その値を引数にした呼び出しの箇所でエラーになる。
次の例はTriangleのクラスの定義後、Shape = Circle | RectにTriangleを追加していない場合である。
print(area(Triangle(2.0, 3.0)))
# mypy
# error: Argument 1 to "area" has incompatible type "Triangle"; expected "Circle | Rect" [arg-type]
# pyright
# error: Argument of type "Triangle" cannot be assigned to parameter "shape" of type "Shape" in function "area"
Triangleの値を引数にした呼び出しが無ければエラーは発生せず、areaのcaseの不足も検出されない。
ガード付きのcaseのクラスは処理済みにならない
ガードはcaseのパターンの後のifの条件で、パターンに一致し、条件も成立した場合だけcaseの本体を実行する。
def area(shape: Shape) -> float:
match shape:
case Circle(radius=r) if r > 0:
return 3.14159 * r * r
case Rect(width=w, height=h):
return w * h
case _:
assert_never(shape)
# mypy
# error: Argument 1 to "assert_never" has incompatible type "Circle"; expected "Never" [arg-type]
# pyright
# error: Argument of type "Circle" cannot be assigned to parameter "arg" of type "Never" in function "assert_never"
# Type "Circle" is not assignable to type "Never" (reportArgumentType)
r > 0が不成立のCircleの値は次のcaseで判定されるので、ガード付きのcaseのCircleは処理済みにならず、case _:のshapeはCircle型と判定される。
ガードの条件が不成立のCircleの値の処理には、ガード無しのcase Circle():を追加する。
TypedDictのUnion型のマッピングパターンはmypyとpyrightで判定が異なる
TypedDict は実行時にはdictなので、クラスパターンでは分岐できない。
判別用のキーのあるTypedDictのUnion型は、マッピングパターン(case {"kind": "circle"}:)で分岐できるが、pyrightは値の型を限定し、mypyは限定しない。
次のCircleDとRectDは、図形の例を辞書の形式にした説明用のTypedDictである。
from typing import Literal, TypedDict, assert_never
class CircleD(TypedDict):
kind: Literal["circle"]
radius: float
class RectD(TypedDict):
kind: Literal["rect"]
width: float
height: float
ShapeD = CircleD | RectD
def area(d: ShapeD) -> float:
match d:
case {"kind": "circle"}:
return 3.14159 * d["radius"] * d["radius"]
case {"kind": "rect"}:
return d["width"] * d["height"]
case _:
assert_never(d)
# mypy
# error: TypedDict "RectD" has no key "radius" [typeddict-item]
# error: TypedDict "CircleD" has no key "width" [typeddict-item]
# error: TypedDict "CircleD" has no key "height" [typeddict-item]
# error: Argument 1 to "assert_never" has incompatible type "CircleD | RectD"; expected "Never" [arg-type]
# pyrightの出力: 0 errors, 0 warnings, 0 informations
pyrightはマッピングパターンのkindの値でdをCircleD型とRectD型に限定し、mypyはdをCircleD | RectD型のまま判定する。
判別用のキーの値の==の比較による分岐なら、TypedDictのままで両方の型チェッカーがdを限定する。
def area(d: ShapeD) -> float:
# 判別用のキーの値を == で比べると、両方の型チェッカーが d を絞り込む
if d["kind"] == "circle":
return 3.14159 * d["radius"] * d["radius"]
elif d["kind"] == "rect":
return d["width"] * d["height"]
else:
assert_never(d)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
実行時のmatch文は網羅性を確認しない
網羅性の確認は型チェッカーだけの機能である。
言語リファレンス の規定では、実行時のmatch文は一致するcaseがなければ何も実行しない。
def area_missing(shape: Shape) -> float:
match shape:
case Circle(radius=r):
return 3.14159 * r * r
print(area_missing(Rect(2.0, 3.0)))
# 実行時の出力
# None
PEP 622の初期の案は、一致するcaseが無い場合に例外を送出する仕様だった。
PEP 622の却下した案の節 では、例外が必要なら書き手が明示的に送出すべきだという意見(Explicit Is Better Than Implicit)が採用された。
この節では、バリアントの集合が確定した場合の不足は、実行前の型チェッカーが警告できるとしている。
case _:のassert_neverは、castや型の注釈のない入力で想定外の値が到達した場合に、実行時にAssertionErrorを送出する。


