PEP 673 Self type

Authors

  • Pradeep Kumar Srinivasan <gohanpra at gmail.com>,

  • James Hilton-Balfe <gobot1234yt at gmail.com>

Sponsor: Jelle Zijlstra <jelle.zijlstra at gmail.com>

Acceptance

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.