typing icon indicating copy to clipboard operation
typing copied to clipboard

Get generic of typevar

Open STofone opened this issue 8 months ago • 3 comments

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

STofone avatar May 13 '25 09:05 STofone

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 avatar May 14 '25 16:05 RBerga06

@RBerga06 I'm already using this way。 But It become so complicated when the generic class has multiple generics

STofone avatar May 15 '25 03:05 STofone

Probably also relevant: Associated types on generics (https://github.com/python/mypy/issues/7790) and this StackOverflow question.

RBerga06 avatar May 21 '25 14:05 RBerga06