PEP 673 Self type ¶
Acceptance ¶
-
https://mail.python.org/archives/list/python-dev@python.org/thread/J7BWL5KWOPQQK5KFWKENVLXW6UGSPTGI/
Hello Pradeep, James and Jelle,
The Steering Council discussed PEP 673 – Self Type, and unanimously decided to accept it. Congratulations!
Please change the PEP status to Accepted, and merge the change to Python 3.11, at your convenience.
Happy typing!
-
Petr (on behalf of the Python Steering Council)
Self type example 1 ¶
This is a huge one, because it is such a common pattern .
There now is a Self type that describes the current class. This is perfect for classes that return self (for easy chaining) or a new instance (including classmethods!):
# Before
Self = TypeVar("Self", bound="Vector")
class Vector:
def square(self: Self) -> Self:
return self**2
@classmethod
def from_coords(
cls: Type[Self],
*,
x: float,
y: float,
) -> Self:
return cls(x, y)
# After
class Vector:
def square(self) -> Self:
return self**2
@classmethod
def from_coords(
cls,
*,
x: float,
y: float,
) -> Self:
return cls(x, y)
If you are tempted to type the name of class in a return annotation as a string, consider Self - it’s more accurate as a return most of the time.