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

Type variables bounded by generic types cannot be used with Type #3148

Closed
pkch opened this issue Apr 9, 2017 · 5 comments
Closed

Type variables bounded by generic types cannot be used with Type #3148

pkch opened this issue Apr 9, 2017 · 5 comments

Comments

@pkch
Copy link
Contributor

pkch commented Apr 9, 2017

T = TypeVar('T')
class X(Generic[T]): ...

U = TypeVar('U', bound=X[T])  # Invalid type "test.T"
def f(cls: Type[U]) -> U:  # Unsupported type Type["U"]
    return cls()

At first glance, this is a duplicate of #2756 . However, that issue is about the first error message, and this issue is about the second.

In #2756 (as here), the "Invalid type test.T" message goes away once we provide a concrete parameter for X, like U = TypeVar('U', bound=X[int]). The "Unsupported type Type["U"] message, however, never goes away as long as X remains generic.

I have a use case: f is supposed to convert some data into a U; the first argument is the class into which it is supposed to convert. The function uses some methods that are defined in class X, that's why I need to bound U.

@ilevkivskyi
Copy link
Member

PEP 484 and typing docs currently allow only a class, a union of classes, and Any as arguments for Type[] and explicitly prohibit other constructs:

The only legal parameters for Type are classes, unions of classes, and Any.

I could see possible benefits for allowing also type variables, but I think this needs discussion.

@pkch
Copy link
Contributor Author

pkch commented Apr 9, 2017

Here is my use case for this feature.

BTW, if type variables are prohibited in Type, why does this type check?

T = TypeVar('T')
def f(cls: Type[T]) -> T:  # ok
    return cls()

@ilevkivskyi
Copy link
Member

@pkch Good point, there is some contradiction in PEP 484, on one hand it prohibits anything except classes, unions of classes, and Any, on the other hand it explicitly allows Type[T] as an annotation in the section on self-types.

@gvanrossum
Copy link
Member

I guess we'll have to update that part of PEP 484.

@pkch
Copy link
Contributor Author

pkch commented Apr 10, 2017

Actually, type variables cannot be bound by generic types (with a free parameter) as discussed in #2756 . (The reason I thought they could was due to #3153; once that's fixed, this issue will disappear.)

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

No branches or pull requests

3 participants