Skip to content

5 - PEP 673 Self Type

Accepted PEP, will be part of Python 3.11. The main use cases are methods which return instance(s) of their class. This will simplify especially inheritance related usages. Example from the PEP:

TODO

Read more
The code

Left:

from typing import TypeVar

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


class Shape:
    def set_scale(self: TShape, scale: float) -> TShape:
        self.scale = scale
        return self


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

Right:

from typing import Self


class Shape:
    def set_scale(self, scale: float) -> Self:
        self.scale = scale
        return self


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