Repository navigation
Supporting Self references to class-scoped type aliases? #11553
Replies: 1 comment
|
Short answer: What you're describing is generally called an associated type, and it can already be expressed today — not with Why What to do instead — parameterize the base class: from typing import Generic, TypeVar
class C: ...
class D(C): ...
ProfileT = TypeVar("ProfileT", bound=C)
class Widget(Generic[ProfileT]):
profile_class: type[ProfileT]
def func(self) -> ProfileT:
return self.profile_class()
class SpecialWidget(Widget[D]):
profile_class = D
reveal_type(SpecialWidget().func()) # D
reveal_type(Widget[C]().func()) # CThe Has it been discussed? Yes — "associated types / abstract type members" has come up several times in the typing community. If you'd like to push for dedicated syntax, python/typing discussions is the right venue, since it would need to be specified for all type checkers, not just pyright. For your immediate need, though, the generic-base-class pattern above should fully cover it. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There is currently no way to refer to a class-scoped type alias associated with the current subclass from a method defined in a base class.
Here is a simplified example: I create two classes, A and B, and B is a subclass of A. and I define
TypeOfSomeValueof A and B as C and D respectively. Also, assume function func of A and B returns C and D respectively. As code shown below:I would like to statically express the return type of func (the
???above), which should correspond to the class'sTypeOfSomeValuetype alias. However, I couldn't find any way to express this relationship.Currently,
Selfrefers to the current class itself, but there seems to be no way to refer to a type alias associated withSelf.I would like to refer to the current class's type alias from methods defined in a base class, without hard coding the current class name in every subclass of A.
One possible way is something like
Self.TypeOfSomeValue(which I think might be user-friendly). However, there might be other better solutions.For example, an imagined syntax similar to
Self.TypeOfSomeValuewill work as follows:Then return value of
A.func()will be C, and that ofB.func()will be D.This is essentially an "associated type" relationship: My use case is a GUI framework where each widget subclass has its own associated Profile type. Methods implemented in the base Widget class should return the subclass's corresponding profile type, but I currently cannot express this relationship statically.
Has this idea been discussed before? If not, do you think something like this would be a reasonable addition to the typing ecosystem?
All reactions