# PythonのProtocolと構造的部分型

## Protocolとは

PythonのProtocolとは、引数に要求するメソッドや属性の形を型として定義する仕組みである。
Protocolを引数の型にした関数は、継承関係に関係なく、要求したメソッドを備えた値を引数にできる。
継承関係ではなくメンバーの形で型の適合を判定するこの性質を、構造的部分型（structural subtyping）と呼ぶ。

- 抽象基底クラス（ABC）を引数の型にした関数では、必要なメソッドを備えていても、そのABCを継承していないクラスは型エラーになる
  - 通常のクラスの互換はメソッドの有無ではなく継承関係で判定される
  - 実行時には問題なく動き、型チェッカーが拒否する
- 関数に必要なメンバーだけをProtocolに定義して引数の型にすると、継承していないクラスも引数にできる
  - 標準ライブラリや外部ライブラリのように、後から基底クラスを追加できないクラスにも適用できる
  - 通常のクラスを引数の型にした場合は、これまでどおり継承関係で判定される
- 適合はメンバーの名前とシグネチャで判定され、書き込み可能な属性は型の一致が必要になる
- 名前とシグネチャが偶然一致したメソッドも適合し、そのままでは`isinstance()`に指定できない

## 独自のABCへの適合には継承が必要になる

以降はファイルやソケットのように`close()`メソッドで後始末をするオブジェクトを引数とする関数を例にする。
`Closer`や`FileLike`など、コード例のクラス名はすべて説明のために定義したものである。

Protocolなしで`close()`を要求すると、次のようなABCになる。

```python
from abc import ABC, abstractmethod

class Closer(ABC):
    @abstractmethod
    def close(self) -> None: ...

class FileLike:
    def close(self) -> None:
        print("closed")

def shutdown(c: Closer) -> None:
    c.close()

shutdown(FileLike())
# mypy
# error: Argument 1 to "shutdown" has incompatible type "FileLike"; expected "Closer"  [arg-type]
# pyright
# error: Argument of type "FileLike" cannot be assigned to parameter "c" of type "Closer" in function "shutdown"
#   "FileLike" is not assignable to "Closer" (reportArgumentType)
```

`FileLike`は`close()`を備えており、実行すると`closed`と表示され正常に終了する。
それでも型チェッカーはエラーにする。
引数の型が`Closer`の関数には、`Closer`を継承したクラスしか指定できないからである。

自分で定義したクラスなら`Closer`を継承させて解決できる。
しかし、標準ライブラリや外部ライブラリのクラスには後から基底クラスを追加できない。
ABCの`register()`で後から登録しても、このエラーは解消しない。
`register()`は実行時の`isinstance()`のための仕組みで、[mypyは対応していない](https://github.com/python/mypy/issues/2922)。

## 継承で判定する部分型とメンバーの形で判定する部分型

型Aを型Bの代わりに使用できるか（AがBの部分型か）を判定する方法には、継承の宣言による方法と、メンバーの形による方法がある。

| 決め方 | AがBの部分型になる条件 | 採用している言語の例 |
|---|---|---|
| 名前的部分型（nominal subtyping） | Aの定義でBを継承・実装すると宣言している | Java、C#、Pythonの通常のクラス |
| 構造的部分型（structural subtyping） | Bが要求するメンバーを、Aがすべて互換なシグネチャで備えている | Goのinterface、TypeScriptのオブジェクトの型 |

```mermaid
flowchart BT
  subgraph P["Protocol: メソッドの形で判定"]
    direction BT
    Resource["class Resource<br/>継承なし"] -->|適合| SC["SupportsClose(Protocol)"]
    StringIO["io.StringIO<br/>継承なし"] -->|適合| SC
  end
  subgraph ABC["ABC: 継承の宣言で判定"]
    direction BT
    R["class R(Closer)<br/>継承あり"] -->|適合| Closer["Closer(ABC)"]
    FileLike["class FileLike<br/>継承なし"] -.->|型エラー| Closer
  end
```

前節の`FileLike`が`Closer`の部分型にならなかったのは、Pythonの通常のクラスが名前的部分型で判定されるからである。

Pythonは両方を併用する。
要求を定義する側のクラスを`Protocol`にすると、そのクラスへの適合をメンバーの形で判定する。
`Protocol`でない通常のクラスへの適合は、従来どおり継承関係で判定する。
PEP 544はすべてのクラスを構造的に判定する案を [却下している](https://peps.python.org/pep-0544/#make-every-class-a-protocol-by-default)。
理由は`isinstance()`の意味が継承関係に基づいていることと、多くのクラスはメソッドの実装を多数含み、Protocolにするにはインターフェースが過剰なことである。

## Protocolの定義と使用方法

Protocol自体は [PEP 544](https://peps.python.org/pep-0544/) で導入され、[Python 3.8から](https://docs.python.org/3/library/typing.html#typing.Protocol) `typing`モジュールにある。

ただしコード例は`collections.abc`の型に [`[]`で型引数を指定できる](https://docs.python.org/3/library/collections.abc.html) Python 3.9以降を前提にしている。

`typing.Protocol`を継承したクラスに、要求するメソッドを定義する。
本体は`...`でよい。

```python
from typing import Protocol

class SupportsClose(Protocol):
    def close(self) -> None: ...

class Resource:
    def close(self) -> None:
        print("closed")

def shutdown(resource: SupportsClose) -> None:
    resource.close()

shutdown(Resource())  # ok
```

`Resource`は`SupportsClose`を継承していないが、`close(self) -> None`を備えているので型エラーにならない。

`close()`のないクラスを引数にするとエラーになる。
pyrightは不足しているメンバーの名前まで表示する。

```python
class Empty:
    pass

shutdown(Empty())
# mypy
# error: Argument 1 to "shutdown" has incompatible type "Empty"; expected "SupportsClose"  [arg-type]
# pyright
# error: Argument of type "Empty" cannot be assigned to parameter "resource" of type "SupportsClose" in function "shutdown"
#   "Empty" is incompatible with protocol "SupportsClose"
#     "close" is not present (reportArgumentType)
```

このコードを実行すると`AttributeError: 'Empty' object has no attribute 'close'`で異常終了する。
Protocolを引数の型にすれば、この誤りを実行前に検出できる。

### 標準ライブラリのクラスもProtocolに適合する

標準ライブラリなど自分で変更できないクラスが引数になる関数では、Protocolを型にするとよい。

次の`Readable`が要求するのは、戻り値が文字列の`read()`である。
引数の後ろの`/`は、それより前の引数を位置専用にする記法である。
ここで指定したのはキーワード引数としての呼び出しを禁止し、引数名の一致を適合の条件から除外するためである（理由は「引数名の扱いはmypyとpyrightで異なる」で説明する）。

```python
from io import StringIO
from typing import Protocol

class Readable(Protocol):
    def read(self, size: int = -1, /) -> str: ...

def read_all(source: Readable) -> str:
    return source.read()

print(read_all(StringIO("hello")))  # ok
with open(__file__, encoding="utf-8") as source:
    print(read_all(source))  # ok
```

`StringIO`もテキストモードの`open()`の戻り値も、`Readable`を継承していないが、mypyとpyrightのどちらでもエラーにならない。

## メソッドがProtocolに適合する条件

適合の判定ではメソッドの名前と、シグネチャ全体の互換性を確認する。
基準はProtocolを引数の型にした関数が、定義どおりにメソッドを呼び出して失敗しないかどうかである。

Protocol側が`def m(self, x: Animal) -> Animal`のとき、実装側の差ごとの結果は次のとおりである。

| 実装側の差 | 例 | 結果 |
| --- | --- | --- |
| 戻り値を部分型にする | `-> Dog` | 適合する |
| 引数を上位の型にする | `x: object` | 適合する |
| 引数を部分型にする | `x: Dog` | 適合しない |
| 必須の引数を追加する | `x: Animal, force: bool` | 適合しない |
| 引数名を変更する（位置専用でない場合） | `y: Animal` | pyrightだけがエラーにする |

### 必須の引数を追加したメソッドはProtocolに適合しない

メソッドに必須の引数を追加すると適合しない。
引数の型が`SupportsClose`の関数は`close()`を引数なしで呼ぶので、必須の引数がある`close`では呼び出しに失敗する。

```python
class ForceClose:
    def close(self, force: bool) -> None:
        print(force)

shutdown(ForceClose())
# mypy
# error: Argument 1 to "shutdown" has incompatible type "ForceClose"; expected "SupportsClose"  [arg-type]
# note: Following member(s) of "ForceClose" have conflicts:
# note:     Expected:
# note:         def close(self) -> None
# note:     Got:
# note:         def close(self, force: bool) -> None
# pyright
# error: Argument of type "ForceClose" cannot be assigned to parameter "resource" of type "SupportsClose" in function "shutdown"
#   "ForceClose" is incompatible with protocol "SupportsClose"
#     "close" is an incompatible type
#       Type "(force: bool) -> None" is not assignable to type "() -> None"
#         Extra parameter "force" (reportArgumentType)
```

### 戻り値はProtocol側の型の部分型でも適合する

メソッドの戻り値はProtocol側の型の部分型であってよい。
たとえば説明用のクラス`Animal`とそのサブクラス`Dog`がある場合、`-> Animal`を要求するProtocolに、戻り値の型が`Dog`のメソッドは適合する。
呼び出した側が期待するのは`Animal`で、`Dog`のインスタンスもその条件を満たす。

一方、`int`は`None`の部分型ではない。
そのため、戻り値の型が`int`の`close`は、`-> None`を要求する`SupportsClose`と互換にならない。

```python
class WrongReturn:
    def close(self) -> int:
        return 1

shutdown(WrongReturn())
# pyright
# error: Argument of type "WrongReturn" cannot be assigned to parameter "resource" of type "SupportsClose" in function "shutdown"
#   "WrongReturn" is incompatible with protocol "SupportsClose"
#     "close" is an incompatible type
#       Type "() -> int" is not assignable to type "() -> None"
#         Function return type "int" is incompatible with type "None"
#           "int" is not assignable to "None" (reportArgumentType)
```

### 引数はProtocol側の型の上位の型でも適合する

引数は戻り値と逆の関係で、Protocol側の引数の型そのものか、その上位の型を引数の型にしたメソッドが適合する。
たとえば、`feed()`を`Dog`で呼び出すProtocolに、引数の型が`Animal`の`feed`は適合する。
`Dog`は`Animal`の部分型なので、引数の型が`Animal`のメソッドに`Dog`を指定しても型の条件を満たすからである。

```python
class Animal: ...
class Dog(Animal): ...

class Feeder(Protocol):
    def feed(self, pet: Dog) -> None: ...

class AnyFeeder:
    def feed(self, pet: Animal) -> None:
        print(type(pet).__name__)

def feed_dog(feeder: Feeder) -> None:
    feeder.feed(Dog())

feed_dog(AnyFeeder())  # ok
```

逆に、次の`AnimalFeeder`のように引数の型に`Animal`を要求するProtocolには、引数の型が`Dog`の`feed`は適合しない。
Protocolを引数の型にした関数は`feed()`を`Animal`で呼び出す場合があり、`Dog`を前提にした実装ではその呼び出しに対応できないからである。

```python
class AnimalFeeder(Protocol):
    def feed(self, pet: Animal) -> None: ...

class DogFeeder:
    def feed(self, pet: Dog) -> None:
        print(type(pet).__name__)

def feed_animal(feeder: AnimalFeeder) -> None:
    feeder.feed(Animal())

feed_animal(DogFeeder())
# pyright
# error: Argument of type "DogFeeder" cannot be assigned to parameter "feeder" of type "AnimalFeeder" in function "feed_animal"
#   "DogFeeder" is incompatible with protocol "AnimalFeeder"
#     "feed" is an incompatible type
#       Type "(pet: Dog) -> None" is not assignable to type "(pet: Animal) -> None"
#         Parameter 1: type "Animal" is incompatible with type "Dog"
#           "Animal" is not assignable to "Dog" (reportArgumentType)
```

引数は上位の型でも戻り値は部分型でも適合するという関係が、[Pythonの型ヒントと共変・反変・不変](https://kdot.co.jp/kdotdev/python-covariance-contravariance-variance) で説明した反変と共変の関係である。

### 引数名の扱いはmypyとpyrightで異なる

位置専用の引数の名前は適合の判定の対象外だと、型の仕様は [定めている](https://typing.python.org/en/latest/spec/callables.html#parameter-kinds) が、通常の引数の名前の扱いは定めていない。
この点は型チェッカーによって判定が異なり、前節の`Readable`から`/`を削除して実装側の引数名を`n`に変更すると、pyrightはエラーにし、mypyはエラーにしない。

```python
class Readable(Protocol):
    def read(self, size: int = -1) -> str: ...

class R:
    def read(self, n: int = -1) -> str:
        return "text"

read_all(R())
# mypy
# Success: no issues found in 1 source file
# pyright
# error: Argument of type "R" cannot be assigned to parameter "source" of type "Readable" in function "read_all"
#   "R" is incompatible with protocol "Readable"
#     "read" is an incompatible type
#       Type "(n: int = -1) -> str" is not assignable to type "(size: int = -1) -> str"
#         Parameter name mismatch: "size" versus "n" (reportArgumentType)
```

pyrightはProtocolを引数の型にした関数が`source.read(size=10)`のようにキーワード引数で呼ぶ可能性を考慮し、引数名の不一致をエラーにする。
mypyはこれをエラーにしない。
Protocolの引数を`/`で位置専用にすればキーワード引数による呼び出しが発生せず、どちらの型チェッカーでもエラーにならない。
標準ライブラリのクラスのように引数名を制御できない相手を対象にするProtocolでは、位置専用にしておくのが安全である。
Protocol側の`/`は、実装側のシグネチャを変更しない。
この例の`R.read`は、`n`をキーワード引数として指定できる。

## Protocolのメンバーに属性を定義する

Protocolにはメソッドと属性の両方を定義できる。
次の例の`Named`は名前の属性を要求するProtocolで、`A`と`B`は適合の可否を示すための説明用のクラスである。

```python
from typing import Protocol

class Named(Protocol):
    name: str

class A:
    def __init__(self) -> None:
        self.name: str = "Alice"

def rename(person: Named) -> None:
    person.name = "Bob"

rename(A())  # ok
```

Protocolに`name: str`と定義した属性は、読み書きの両方を要求する。
setterのないプロパティだけを備えたクラスは適合しない。

```python
class B:
    @property
    def name(self) -> str:
        return "Alice"

rename(B())
# mypy
# error: Argument 1 to "rename" has incompatible type "B"; expected "Named"  [arg-type]
# note: Protocol member Named.name expected settable variable, got read-only attribute
```

`rename(B())`では`person.name`への代入が発生し、実行時に`AttributeError: property 'name' of 'B' object has no setter`になる。
型チェッカーの判定はこの実行時の失敗と一致している。

### 書き込み可能な属性はProtocol側の型と一致させる

同じ理由で、書き込み可能な属性は型が一致しなければ適合しない。
次の例の`Owner`は属性`pet`の型が`Dog`で、`Dog`は`Animal`の部分型である。
それでも、属性`pet: Animal`を要求するProtocol`HasPet`には適合しない。

```python
class Animal: ...
class Dog(Animal): ...

class HasPet(Protocol):
    pet: Animal

class Owner:
    def __init__(self) -> None:
        self.pet: Dog = Dog()

def show_pet(owner: HasPet) -> None:
    print(type(owner.pet).__name__)

show_pet(Owner())
# mypy
# error: Argument 1 to "show_pet" has incompatible type "Owner"; expected "HasPet"  [arg-type]
# note: Following member(s) of "Owner" have conflicts:
# note:     pet: expected "Animal", got "Dog"
# pyright
# error: Argument of type "Owner" cannot be assigned to parameter "owner" of type "HasPet" in function "show_pet"
#   "Owner" is incompatible with protocol "HasPet"
#     "pet" is invariant because it is mutable
#     "pet" is an incompatible type
#       "Dog" is not assignable to "Animal" (reportArgumentType)
```

pyrightのメッセージにある「invariant because it is mutable」がその理由である。
引数の型が`HasPet`の関数では、`owner.pet = Animal()`という代入はエラーにならない。
`Owner`の適合を許可すると、`Dog`のみを想定した`Owner.pet`への`Animal`の代入まで許可することになる。
PEP 544も書き込み可能な属性を共変として判定する案をこの理由で [却下している](https://peps.python.org/pep-0544/#covariant-subtyping-of-mutable-attributes)。

読み取りだけで十分な場合は、setterのないプロパティとして要求する。
`Dog`は`Animal`の部分型なので、取得した値は`Animal`として使用できる。
読み取り専用の属性はProtocol経由の代入を要求しないため、`pet: Dog`の属性を備えた`Owner`も適合する。

```python
class HasPetRO(Protocol):
    @property
    def pet(self) -> Animal: ...

def show_pet(owner: HasPetRO) -> None:
    print(type(owner.pet).__name__)

show_pet(Owner())  # ok
```


## Protocolの限界

### 名前が偶然一致したメソッドもProtocolに適合する

構造的部分型では名前とシグネチャが一致するメソッドは意味が異なっても適合する。
次の例では「発射する」を意味する`fire()`を要求するProtocol`Shootable`と、「解雇する」を意味する`fire()`のあるクラス`Employee`を定義する。

```python
class Shootable(Protocol):
    def fire(self) -> None: ...

class Employee:
    def fire(self) -> None:
        print("employment terminated")  # 解雇する

def shoot(target: Shootable) -> None:
    target.fire()

shoot(Employee())  # 型チェックは通る
```

「発射する」の`fire`を要求する関数の引数に、「解雇する」の`fire`を備えた`Employee`も指定できる。
名前的部分型では`Employee`を`Shootable`の部分型にするには継承の宣言が必要なので、宣言しない限りこの混同は発生しない。
メソッドの名前が一般的な語（`run`、`get`、`fire`など）で構成されたProtocolでは、意味の異なるメソッドを備えたクラスまで適合することがある。

### Protocolをisinstanceに指定できない

Protocolを`isinstance()`の第2引数にすると、型チェッカーでエラーになり、実行時も`TypeError`になる。
次の例の`SupportsClose`と`Resource`は「Protocolの定義と使用方法」で定義したクラスである。

```python
isinstance(Resource(), SupportsClose)
# mypy
# error: Only @runtime_checkable protocols can be used with instance and class checks  [misc]
# 実行時
# TypeError: Instance and class checks can only be used with @runtime_checkable protocols
```

`@runtime_checkable`を指定すれば、`isinstance()`で判定できる。
ただし実行時に判定するのはメンバーの有無だけで、シグネチャは比較しない。
`close(self, force: bool)`を備えたクラスでも`isinstance()`は`True`になる。
PEP 544がデフォルトで`isinstance()`への指定を禁止したのは、この判定が [当てにならないため](https://peps.python.org/pep-0544/#support-isinstance-checks-by-default) である。

### メンバーの存在を任意にする指定はできない

TypeScriptのinterfaceは`name?: string`のように省略可能なメンバーを定義できるが、Protocolにはこの機能がない。
PEP 544はPythonでのこの需要がまだ明確でないとして [採用を保留している](https://peps.python.org/pep-0544/#support-optional-protocol-members)。

## ProtocolとABCの使い分け

PEP 544はProtocolを名前的部分型の代わりではなく [補完と位置づけ](https://peps.python.org/pep-0544/#nominal-vs-structural-subtyping)、利用者が選択できるようにしている。

| 状況 | 選択する方 | 理由 |
|---|---|---|
| 自分で変更できないクラス（標準ライブラリ、外部ライブラリ）が引数になる | Protocol | 継承を後から追加できない |
| 関数に必要なメンバーだけを要求したい | Protocol | 要求を最小限にすれば、適合するクラスの範囲が拡大する |
| 「この役割を実装した」ことを明示し、同名のメソッドの混同を回避したい | ABC | 継承の宣言がないと部分型にならない |
| 基底クラスに定義したメソッドの実装を、各クラスに継承させたい | ABC | Protocolの実装は、構造的に適合したクラスには継承されない |
| 実行時に`isinstance()`で分岐したい | ABC | Protocolは`@runtime_checkable`でもメンバーの有無しか判定しない |

`collections.abc`の`Iterable`や`Sized`なども、型チェッカーは [Protocolとして判定する](https://peps.python.org/pep-0544/#changes-in-the-typing-module)。
`__iter__`を備え、その戻り値の型が`Iterator`であるクラスは、継承しなくても`Iterable`型の引数に指定できる。

## 参考

- [PEP 544 – Protocols: Structural subtyping (static duck typing)](https://peps.python.org/pep-0544/)
- [Typing specification: Protocols](https://typing.python.org/en/latest/spec/protocol.html)
- [typing — Support for type hints: Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol)
