Skip to content
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

TypeVar Should Accept Arguments When Bound To Generic #8278

Closed
rmorshea opened this issue Jan 15, 2020 · 2 comments
Closed

TypeVar Should Accept Arguments When Bound To Generic #8278

rmorshea opened this issue Jan 15, 2020 · 2 comments

Comments

@rmorshea
Copy link

rmorshea commented Jan 15, 2020

I've posted about this on gitter but haven't gotten a response. Could someone help me understand how I would construct the type spec for a function def (G[T]) -> G[List[G]] where G is any subclass of MyGeneric class. My current approach results in the commented error:

from typing import TypeVar, Generic

Val = TypeVar("Val")

class MyGeneric(Generic[Val]):
    def __call__(self, a: Val) -> Val: ...

T = TypeVar("T")
G = TypeVar("G", bound=MyGeneric)

def listify_my_generic(g: G[T]) -> G[List[T]]: ...  # error: Type variable "G" used with arguments

Here's a playground link:

https://mypy-play.net/?mypy=0.750&python=3.8&gist=290ef32f0638a648674b98873a263d6f

@rmorshea rmorshea changed the title Question - Allow Generic Subclasses with TypeVar TypeVar Should Accept Arguments When Bound To Generic Jan 15, 2020
@rmorshea
Copy link
Author

rmorshea commented Jan 15, 2020

Ok, I've managed to create a work around:

from typing import TypeVar, Generic, List

Val = TypeVar("Val")

class MyGeneric(Generic[Val]):
    def __init__(self, a: Val): ...

T = TypeVar("T")

SingleG = MyGeneric[T]
ListG = MyGeneric[List[T]]

def listify_my_generic(g: SingleG[T]) -> ListG[T]: ...

reveal_type(listify_my_generic(MyGeneric(1)))  # note: Revealed type is 'main.MyGeneric[builtins.list[builtins.int*]]'

However it would be nice if the example above worked - the work around requires more typing and is only able to communicate what's happening so long as descriptive variable names are used.

@JukkaL
Copy link
Collaborator

JukkaL commented Jan 15, 2020

This looks essentially the same as python/typing#548. Discussion can continue there. More generally, this is a type system enhancement and we generally discuss them in the typing issue tracker (or typing-sig@).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants