typing
typing copied to clipboard
Get generic of typevar
support something like this
class A[T]:
def __init__(self, t: T):
self.t = t
class B:
def x[TA: A](self, a: TA) -> TA.T:
return a.t
This reminds me of HKTs (#548).
However, I think this specific example is simple enough you don't really need that feature, this should be sufficient:
class B:
def x[T](self, a: A[T]) -> T:
return a.t
See how Pyright handles this at Pyright playground.
Full code sample
class A[T]:
def __init__(self, t: T):
self.t = t
class B:
def x[T](self, a: A[T]) -> T:
return a.t
# usage example
a0 = A(42)
reveal_type(a0) # A[int]
reveal_type(B().x(a0)) # int
a1 = A("example")
reveal_type(a1) # A[str]
reveal_type(B().x(a1)) # str
# it still works with subclasses of A
class A2[T](A[T]):
pass
class A3(A[float]):
pass
a2 = A2("test")
reveal_type(a2) # A2[str]
reveal_type(B().x(a2)) # str
a3 = A3(3.14)
reveal_type(a3) # A3
reveal_type(B().x(a3)) # float
@RBerga06 I'm already using this way。 But It become so complicated when the generic class has multiple generics
Probably also relevant: Associated types on generics (https://github.com/python/mypy/issues/7790) and this StackOverflow question.