# 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`は図形の面積を計算する説明用の関数である。

```python
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](https://peps.python.org/pep-0634/#class-patterns) のクラスパターンで、値が`Circle`のインスタンスの場合に一致し、`radius`属性の値を`r`に代入する。
型チェッカーは`case Circle(...)`の分岐の`shape`を`Circle`型、`r`を`float`型と判定する。
この条件の分岐による型の限定を、[型の絞り込み（type narrowing）](https://kdot.co.jp/kdotdev/python-type-narrowing) と呼ぶ。

クラスパターンの位置引数（`case Rect(w, h):`）も使用できる。
[dataclassesのドキュメント](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass) の規定では、`dataclass`はkeyword-onlyでないフィールドの定義順の名前を`__match_args__`に設定する。

`area`の末尾には`return`が無いが、エラーにはならない。
2つの`case`で`Shape`の全部のバリアントを処理したので、型チェッカーは`match`の後の関数の末尾を到達不能と判定する。

## バリアントの追加で処理の不足が型エラーになる

`Shape`への三角形の`Triangle`の追加後、`area`が変更前のままなら、`area`の定義がエラーになる。

```python
@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`](https://docs.python.org/3/library/typing.html#typing.assert_never) の呼び出しでは、未処理のバリアントのクラス名がエラー文に表示される。
次の例は`Circle`と`Rect`の`Shape`で、`Rect`の`case`が無い。

```python
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の記事](https://kdot.co.jp/kdotdev/python-never-assert-never) で説明した。

[Union型とisinstanceの記事](https://kdot.co.jp/kdotdev/python-union-isinstance) で説明したとおり、Union型の値の`isinstance`の分岐でも型は限定され、未処理のバリアントは同じエラーになる。

```python
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`がエラーになる。

```python
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](https://peps.python.org/pep-0622/#sealed-classes-as-algebraic-data-types) は、サブクラスの定義を同じモジュールに限定する`@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`を追加していない場合である。

```python
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`の本体を実行する。

```python
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](https://docs.python.org/3/library/typing.html#typing.TypedDict) は実行時には`dict`なので、クラスパターンでは分岐できない。
判別用のキーのあるTypedDictのUnion型は、マッピングパターン（`case {"kind": "circle"}:`）で分岐できるが、pyrightは値の型を限定し、mypyは限定しない。
次の`CircleD`と`RectD`は、図形の例を辞書の形式にした説明用のTypedDictである。

```python
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`を限定する。

```python
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文は網羅性を確認しない

網羅性の確認は型チェッカーだけの機能である。
[言語リファレンス](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement) の規定では、実行時のmatch文は一致する`case`がなければ何も実行しない。

```python
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の却下した案の節](https://peps.python.org/pep-0622/#check-exhaustiveness-at-runtime) では、例外が必要なら書き手が明示的に送出すべきだという意見（Explicit Is Better Than Implicit）が採用された。
この節では、バリアントの集合が確定した場合の不足は、実行前の型チェッカーが警告できるとしている。
`case _:`の`assert_never`は、`cast`や型の注釈のない入力で想定外の値が到達した場合に、実行時に`AssertionError`を送出する。
