# PythonのSelf型でメソッドの戻り値をサブクラスの型にする

## Self型とは

Pythonの`Self`型とは、メソッドの型注釈で使用する`typing`の特殊な注釈で、型チェッカーの判定では呼び出し対象の値の型と同一になる。
判定の対象は実行時のクラスではなく、変数や式の型注釈と推論の結果の型（静的型）である。
`self`を戻り値にするメソッドの戻り値の型を`Self`にすると、サブクラスの型の値の呼び出しの結果はサブクラスの型になる。

- 戻り値の型に定義中のクラス名を記述したメソッドは、サブクラスのインスタンスの呼び出しでも結果が親クラスの型になり、メソッドチェーンの途中のサブクラスのメソッドの呼び出しは、実行時には成功するが型エラーになる
- 戻り値の型を`Self`にすると、`Circle().set_scale(0.5)`の結果は`Circle`型になり、後続の`Circle`のメソッドの呼び出しもエラーにならない
  - 親クラスのメソッドのサブクラスごとの再定義は不要である
  - 静的型が`Shape`の変数の呼び出しの結果は、実行時の値が`Circle`でも`Shape`型である
- `Self`を戻り値の型にしたメソッドで`Shape()`のように特定のクラスのインスタンスを戻り値にすると、エラーになる
  - サブクラスの呼び出しで親クラスのインスタンスが戻り値になり、サブクラスの属性の参照が実行時に失敗する誤りを、実行前に検出できる
  - クラスの外の関数、`@staticmethod`、型エイリアス（型の別名の定義）には`Self`を指定できない
- サブクラスが同じメソッドを戻り値の型をクラス名にして再定義すると、孫のクラスでは結果の型がそのクラス名の型になり、型チェッカーはこの再定義をエラーにしない
- 実行時には`Self`による戻り値の確認はなく、`isinstance`の第2引数への指定は`TypeError`になる

## 戻り値の型がクラス名のメソッドの結果は親クラスの型になる

以降の例の診断はmypyとpyrightの標準の設定での出力である。
`reveal_type`は型チェッカーの判定の結果の表示、`assert_type`は判定の結果と指定の型の一致の確認のための関数で、どちらも [Python 3.11以降](https://docs.python.org/3/library/typing.html#typing.assert_type) の`typing`にある。
`Self`も [Python 3.11で](https://docs.python.org/3/library/typing.html#typing.Self) `typing`に追加された。

`Shape`と`Circle`は説明のために定義したクラスで、`set_scale`と`set_radius`は属性を設定して`self`を戻り値にする。
定義中のクラスの名前は、文字列の`"Shape"`の [前方参照](https://kdot.co.jp/kdotdev/python-forward-reference-annotations) で記述する。

```python
from typing import reveal_type


class Shape:
    # 戻り値の型に定義中のクラス名を記述する
    def set_scale(self, scale: float) -> "Shape":
        self.scale = scale
        return self


class Circle(Shape):
    def set_radius(self, r: float) -> "Circle":
        self.radius = r
        return self


reveal_type(Circle().set_scale(0.5))
circle = Circle().set_scale(0.5).set_radius(2.7)
print(circle.scale, circle.radius)
# mypy
# error: "Shape" has no attribute "set_radius"  [attr-defined]
# pyright
# information: Type of "Circle().set_scale(0.5)" is "Shape"
# error: Cannot access attribute "set_radius" for class "Shape"
#   Attribute "set_radius" is unknown (reportAttributeAccessIssue)
# 実行時の出力: 0.5 2.7
```

`set_scale`の戻り値は`Circle`のインスタンスなので、実行時の`set_radius`の呼び出しは成功する。
型チェッカーは戻り値の型の注釈の`Shape`を結果の型にするので、`Shape`にない`set_radius`の呼び出しをエラーにする。
[PEP 673](https://peps.python.org/pep-0673/#motivation) はこの不便を`Self`の導入の動機にしている。

## Selfで戻り値の型を呼び出し元のクラスにする

```python
from typing import Self, assert_type


class Shape:
    # 呼び出したインスタンスの型を戻り値の型にする
    def set_scale(self, scale: float) -> Self:
        self.scale = scale
        return self


class Circle(Shape):
    def set_radius(self, r: float) -> Self:
        self.radius = r
        return self


assert_type(Circle().set_scale(0.5), Circle)
circle = Circle().set_scale(0.5).set_radius(2.7)
print(circle.scale, circle.radius)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
```

戻り値の型をクラス名で記述した場合と異なり、サブクラスごとのメソッドの再定義と戻り値の型の変更は不要である。
`Self`は呼び出し対象の静的型になるので、静的型が`Shape`の値（`Shape`型の引数など）の呼び出しの結果は、実行時の値が`Circle`でも`Shape`型である。

### Selfと型変数の関係

[型の仕様](https://typing.python.org/en/latest/spec/generics.html#self) は、メソッドの`Self`を、定義中のクラスが上限（`bound`）の型変数と同等に判定すると定めている。
この型変数は、定義中のクラスかそのサブクラスの型である。
`Self`の追加の前は、次のように`self`の引数と戻り値に同じ型変数を指定していた。

```python
from typing import TypeVar, assert_type

TShape = TypeVar("TShape", bound="Shape")


class Shape:
    # selfの型と戻り値の型に同じ型変数を指定する
    def set_scale(self: TShape, scale: float) -> TShape:
        self.scale = scale
        return self


class Circle(Shape):
    def set_radius(self, r: float) -> "Circle":
        self.radius = r
        return self


assert_type(Circle().set_scale(0.5), Circle)
circle = Circle().set_scale(0.5).set_radius(2.7)
print(circle.scale, circle.radius)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
```

型変数`TShape`の上限が`Shape`なので、`self`には`Shape`かそのサブクラスのインスタンスが該当し、`Circle`のインスタンスの呼び出しでは`TShape`は`Circle`になる。
PEP 673は、この記述の冗長さと、型変数の上限か`self`の型注釈の記述を省略する誤りの多さを`Self`の動機にしている。
メソッドの本体からの戻り値の型の推論の案は、[明示を優先する方針と、型スタブには本体が存在せず推論できないこと](https://peps.python.org/pep-0673/#allow-the-type-checker-to-infer-the-return-type) を理由に却下された。

### クラスメソッドでインスタンスを生成する

`@classmethod`の戻り値の型にも`Self`を指定でき、[PEP 673](https://peps.python.org/pep-0673/#use-in-classmethod-signatures) は`cls: type[T]`と型変数の宣言の省略を利点にしている。
`cls()`で生成したインスタンスは、`Circle`のクラスメソッドの呼び出しでは`Circle`型になる。
この例の`Circle`は引数なしで生成できるクラスである。
必須の引数を追加したサブクラスでは、`cls()`の呼び出しは実行時に`TypeError`になる。

```python
from typing import Self, assert_type


class Shape:
    scale: float = 1.0

    # clsで生成したインスタンスを戻り値にする
    @classmethod
    def from_config(cls, config: dict[str, float]) -> Self:
        shape = cls()
        shape.scale = config["scale"]
        return shape


class Circle(Shape):
    pass


circle = Circle.from_config({"scale": 1.0})
assert_type(circle, Circle)
print(type(circle).__name__, circle.scale)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時の出力: Circle 1.0
```

通常のメソッドでも、`type(self)()`で生成したインスタンスと`copy.copy(self)`の結果は`Self`型と判定され、エラーにならない。

```python
from copy import copy
from typing import Self, assert_type


class Shape:
    # copyとtype(self)の結果はどちらもSelf型になる
    def copied(self) -> Self:
        return copy(self)

    def fresh(self) -> Self:
        return type(self)()


class Circle(Shape):
    pass


circle = Circle()
assert_type(circle.copied(), Circle)
assert_type(circle.fresh(), Circle)
print(type(circle.copied()).__name__, type(circle.fresh()).__name__)
# mypyの出力: Success: no issues found in 1 source file
# pyrightの出力: 0 errors, 0 warnings, 0 informations
# 実行時の出力: Circle Circle
```

## 引数と属性の型にSelfを指定する

`Self`は戻り値以外の型注釈にも指定できる。
サブクラスでは、引数と属性の型もサブクラスの型になる。

### 引数の型

`same_scale`の引数`other`の型を`Self`にすると、`Circle`のインスタンスの呼び出しでは、`other`の型は`Circle`になる。

```python
from typing import Self, reveal_type


class Shape:
    scale: float = 1.0

    # 引数の型をSelfにする
    def same_scale(self, other: Self) -> bool:
        return self.scale == other.scale


class Circle(Shape):
    pass


reveal_type(Circle().same_scale)
print(Circle().same_scale(Shape()))
print(Shape().same_scale(Circle()))
# mypy
# note: Revealed type is "def (other: Circle) -> bool"
# error: Argument 1 to "same_scale" of "Shape" has incompatible type "Shape"; expected "Circle"  [arg-type]
# pyright
# information: Type of "Circle().same_scale" is "(other: Circle) -> bool"
# error: Argument of type "Shape" cannot be assigned to parameter "other" of type "Circle" in function "same_scale"
#   "Shape" is not assignable to "Circle" (reportArgumentType)
```

`Circle().same_scale(Shape())`はエラーになり、`Shape().same_scale(Circle())`は`Circle`が`Shape`のサブクラスなのでエラーにならない。
実行時にはどちらも`True`を表示する。

### 属性の型

属性の型に`Self`を指定すると、サブクラスのインスタンスの属性はサブクラスの型になる。
次の`Node`は説明のために定義したdataclassで、`next`は次の要素への参照である。
`next`の型を`Node | None`にすると、`NamedNode`の`next`に`Node`のインスタンスを代入でき、`next.name`の参照が実行時に`AttributeError`になる。
[PEP 673](https://peps.python.org/pep-0673/#use-in-attribute-annotations) はこの誤りの防止を属性の`Self`の理由にしている。
dataclassは`next`を`__init__`の引数にするので、`Self`の制限は`__init__`の引数にも適用される。

```python
from dataclasses import dataclass
from typing import Self, reveal_type


@dataclass
class Node:
    value: int
    # 属性の型をSelfにする
    next: Self | None = None


class NamedNode(Node):
    name: str = ""


bad = NamedNode(1, next=Node(2))
good = NamedNode(1, next=NamedNode(2))
reveal_type(good.next)
print(type(bad.next).__name__, type(good.next).__name__)
# mypy
# note: Revealed type is "NamedNode | None"
# Success: no issues found in 1 source file
# pyright
# error: Argument of type "Node" cannot be assigned to parameter "next" of type "NamedNode | None" in function "__init__"
# information: Type of "good.next" is "NamedNode | None"
```

両方の型チェッカーが`good.next`の型を`NamedNode | None`と判定する。
一方で、`NamedNode`の`next`に`Node`のインスタンスを指定する呼び出しは、pyrightだけがエラーにし、mypyはエラーにしない。
[型の仕様](https://typing.python.org/en/latest/spec/generics.html#use-in-attribute-annotations) はこの呼び出しを型エラーとする例を掲載している。
mypyの判定では、dataclassが生成する`__init__`の引数の型の`Self`は、サブクラスでも`Node`のままである。

### ジェネリッククラス

型引数のあるクラスでは、`Self`は型引数を含めたインスタンスの型になる。

```python
from typing import Generic, Self, TypeVar, reveal_type

T = TypeVar("T")


class Box(Generic[T]):
    # Box[int]のインスタンスの呼び出しではSelfはBox[int]になる
    def set_value(self, v: T) -> Self:
        self.value = v
        return self


box = Box[int]().set_value(1)
reveal_type(box)
print(box.value)
# mypy
# note: Revealed type is "Box[builtins.int]"
# pyright
# information: Type of "box" is "Box[int]"
```

## Selfを指定できない場所

`Self`はクラスの定義の中の型注釈でだけ有効である。
[型の仕様](https://typing.python.org/en/latest/spec/generics.html#valid-locations-for-self) が拒否する場所に指定すると、両方の型チェッカーがエラーにする。

| 指定した場所 | mypy | pyright | 型の仕様の理由 |
|---|---|---|---|
| クラスの外の関数 | `Self type is only allowed in annotations within class definition` | `"Self" is not valid in this context` | 対象のクラスがない |
| `@staticmethod` | `Static methods cannot use Self type` | `"Self" is not valid in this context` | 戻り値にする`self`や`cls`がない |
| `Self[int]` | `Self type cannot have type arguments` | `Expected no type arguments for class "Self"` | `self`の引数の型が曖昧になる |
| 型エイリアスの`tuple[Self, Self]` | `Self type cannot be used in type alias target` | `"Self" is not valid in this context` | クラス外の`Self`の扱いが型チェッカーの負担になる |

`self`と型引数が異なるクラスを指定する場合は、[型の仕様](https://typing.python.org/en/latest/spec/generics.html#use-in-generic-classes) は`self`の型をクラス名と型引数で明示することを推奨している。

## 型チェッカーが確認することと確認しないこと

### 特定のクラスのインスタンスを戻り値にする実装

`Self`を戻り値の型にしたメソッドで、`Shape()`のように特定のクラスのインスタンスを戻り値にすると、両方の型チェッカーがエラーにする。

```python
from typing import Self, reveal_type


class Shape:
    # Self型のメソッドの戻り値に特定のクラスのインスタンスを指定する
    def clone(self) -> Self:
        return Shape()


class Circle(Shape):
    radius: float = 2.7


circle = Circle().clone()
reveal_type(circle)
print(type(circle).__name__, flush=True)
print(circle.radius)
# mypy
# error: Incompatible return value type (got "Shape", expected "Self")  [return-value]
# pyright
# error: Type "Shape" is not assignable to return type "Self@Shape"
# information: Type of "circle" is "Circle"
# 実行時の出力: Shape
# AttributeError: 'Shape' object has no attribute 'radius'
```

呼び出し側の`Circle().clone()`の結果は`Circle`型と判定されるが、実行時の値は`Shape`のインスタンスで、`radius`の参照は`AttributeError`になる。
型の仕様はこの実行時のエラーを、特定のクラスのインスタンスを拒否する理由にしている。
サブクラスのインスタンスを生成するには、`cls()`か`type(self)()`を使用する。
サブクラスの`__init__`の引数が親クラスと異なる場合は、生成の呼び出しにもその引数が必要である。

### サブクラスでの再定義

`Self`を戻り値の型にしたメソッドを、サブクラスで戻り値の型をクラス名にして再定義しても、両方の型チェッカーはエラーにしない。

```python
from typing import Self, reveal_type


class Parent:
    def clone(self) -> Self:
        return self


class Child(Parent):
    # 戻り値の型をクラス名にして再定義する
    def clone(self) -> "Child":
        return self


class GrandChild(Child):
    pass


reveal_type(GrandChild().clone())
print(type(GrandChild().clone()).__name__)
# mypy
# note: Revealed type is "Child"
# pyright
# information: Type of "GrandChild().clone()" is "Child"
# 実行時の出力: GrandChild
```

`GrandChild`の`clone`の結果は`Child`型になり、`GrandChild`に固有の属性を参照すると型エラーになる。
継承の途中のクラスでも、再定義するメソッドの戻り値の型は`Self`のまま記述する。

### 実行時の挙動

`Self`は型チェッカーのための記号で、実行時には戻り値の型の確認はない。
`isinstance`の第2引数に指定すると、実行時に`TypeError`になる。

```python
from typing import Self


class Shape:
    # 型チェッカーはエラーにするが、実行時には検査されない
    def broken(self) -> Self:
        return 42


print(Self)
x = Shape()
try:
    print(isinstance(x, Self))
except TypeError as error:
    print(f"TypeError: {error}")
print(x.broken())
# mypy
# error: Incompatible return value type (got "int", expected "Self")  [return-value]
# error: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "_ClassInfo"  [arg-type]
# pyright
# error: Type "Literal[42]" is not assignable to return type "Self@Shape"
# 実行時の出力
# typing.Self
# TypeError: typing.Self cannot be used with isinstance()
# 42
```

`isinstance(x, Self)`は、mypyだけが型エラーにし、pyrightはエラーにしない。
実行時に`self`の型を判定する場合は、`isinstance(x, type(self))`のように`type(self)`を使用する。

## 他の言語の対応する記法とSelfの使い分け

[PEP 673](https://peps.python.org/pep-0673/#resources) は、同様の仕組みの例としてTypeScriptの`this`型とRustの`Self`型を掲載している。
Javaには同等の記法がなく、`Enum<E extends Enum<E>>`のように型引数の上限に自身を含める書き方（F-bounded polymorphism）で表現する。
Pythonの上限付きの型変数の書き方は、型引数をクラスではなくメソッドの`self`に指定する点で異なる。

| 戻り値 | 記述の方法 |
|---|---|
| `self`か`cls()`で生成したインスタンスで、サブクラスではサブクラスの型にする | `Self` |
| サブクラスからの呼び出しでも常に特定のクラスのインスタンス | 戻り値の型にクラス名を記述する |
| Python 3.10以前で`Self`を使用 | [`typing_extensions.Self`](https://typing-extensions.readthedocs.io/en/latest/#typing_extensions.Self) か、上限付きの型変数 |
| `self`と型引数が異なるインスタンス（`Box[int]`のメソッドの`Box[str]`） | `self`の型と戻り値の型をクラス名と型引数で明示する |
