Special type to represent the current enclosed class.
typing.Self
from typing import Self, reveal_type
class Foo:
def return_self(self) -> Self:
...
return self
class SubclassOfFoo(Foo): pass
reveal_type(Foo().return_self()) Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self()) Revealed type is "SubclassOfFoo"
from typing import TypeVar
Self = TypeVar("Self", bound="Foo")
class Foo:
def return_self(self: Self) -> Self:
...
return self
class Eggs:
Self would be an incorrect return annotation here,
as the object returned is always an instance of Eggs,
even in subclasses
def returns_eggs(self) -> "Eggs":
return Eggs()