Description
Feature
Support the pep-673 Self type
pep is at: https://www.python.org/dev/peps/pep-0673/
a rough idea of it is that this code:
from typing import Self
class Widget:
def add_thing(self, value: str) -> Self:
self.value = value
return self
is quasi-equivalent to:
from typing import TypeVar
TWidget = TypeVar("TWidget", bound="Widget")
class Widget:
def add_thing(self: TWidget, value: str) -> TWidget:
self.value = value
return self
Pitch
the appeal of the pep is that for the very common pattern of method-chained object construction, methods can easily indicate they return an object of the same type upon which the method is being invoked. For example if I made class SubWidget(Widget)
, the SubWidget.add_thing()
method reports SubWidget
as the return type automatically. The pattern using TypeVar seems to be more or less equivlant, but is more verbose requiring the declaration of TypeVar objects per class hierarchy as well as that it has to be explicitly present on the "self" parameter in methods.
We are looking for this feature to make our job of integrating typing into SQLAlchemy an easier job. it seems to be a fairly straightforward translation between two idioms.
cc @CaselIT