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以降 のtypingにある。
Selfも Python 3.11で typingに追加された。
ShapeとCircleは説明のために定義したクラスで、set_scaleとset_radiusは属性を設定してselfを戻り値にする。
定義中のクラスの名前は、文字列の"Shape"の 前方参照 で記述する。
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 はこの不便をSelfの導入の動機にしている。
Selfで戻り値の型を呼び出し元のクラスにする
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と型変数の関係
型の仕様 は、メソッドのSelfを、定義中のクラスが上限(bound)の型変数と同等に判定すると定めている。
この型変数は、定義中のクラスかそのサブクラスの型である。
Selfの追加の前は、次のようにselfの引数と戻り値に同じ型変数を指定していた。
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の動機にしている。
メソッドの本体からの戻り値の型の推論の案は、明示を優先する方針と、型スタブには本体が存在せず推論できないこと を理由に却下された。
クラスメソッドでインスタンスを生成する
@classmethodの戻り値の型にもSelfを指定でき、PEP 673 はcls: type[T]と型変数の宣言の省略を利点にしている。
cls()で生成したインスタンスは、Circleのクラスメソッドの呼び出しではCircle型になる。
この例のCircleは引数なしで生成できるクラスである。
必須の引数を追加したサブクラスでは、cls()の呼び出しは実行時にTypeErrorになる。
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型と判定され、エラーにならない。
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になる。
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 はこの誤りの防止を属性のSelfの理由にしている。
dataclassはnextを__init__の引数にするので、Selfの制限は__init__の引数にも適用される。
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はエラーにしない。
型の仕様 はこの呼び出しを型エラーとする例を掲載している。
mypyの判定では、dataclassが生成する__init__の引数の型のSelfは、サブクラスでもNodeのままである。
ジェネリッククラス
型引数のあるクラスでは、Selfは型引数を含めたインスタンスの型になる。
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はクラスの定義の中の型注釈でだけ有効である。
型の仕様 が拒否する場所に指定すると、両方の型チェッカーがエラーにする。
| 指定した場所 | 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と型引数が異なるクラスを指定する場合は、型の仕様 はselfの型をクラス名と型引数で明示することを推奨している。
型チェッカーが確認することと確認しないこと
特定のクラスのインスタンスを戻り値にする実装
Selfを戻り値の型にしたメソッドで、Shape()のように特定のクラスのインスタンスを戻り値にすると、両方の型チェッカーがエラーにする。
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を戻り値の型にしたメソッドを、サブクラスで戻り値の型をクラス名にして再定義しても、両方の型チェッカーはエラーにしない。
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になる。
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 は、同様の仕組みの例として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 か、上限付きの型変数 |
selfと型引数が異なるインスタンス(Box[int]のメソッドのBox[str]) |
selfの型と戻り値の型をクラス名と型引数で明示する |


