Skip to content

Get generic of typevar #1999

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
STofone opened this issue May 13, 2025 · 2 comments
Open

Get generic of typevar #1999

STofone opened this issue May 13, 2025 · 2 comments
Labels
topic: feature Discussions about new features for Python's type annotations

Comments

@STofone
Copy link

STofone commented May 13, 2025

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 STofone added the topic: feature Discussions about new features for Python's type annotations label May 13, 2025
@STofone STofone changed the title Get generic of typevar as typehint Get generic of typevar May 13, 2025
@RBerga06
Copy link

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

@STofone
Copy link
Author

STofone commented May 15, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: feature Discussions about new features for Python's type annotations
Projects
None yet
Development

No branches or pull requests

2 participants