Description
I don't think there's a way to write this code in a type-safe way:
from typing import TypeVar, Generic, List, Callable
T = TypeVar('T')
class X(Generic[T]):
def f(self) -> T: ...
C = TypeVar('C', bound=X)
def g(cls: Callable[[], C]) -> None:
x: ??? = cls().f()
There is no precise type I can use in place of ???
.
reveal_type(cls().f())
tells me Revealed type is 'T`1'
, but that's not much help because I can't say x: T
(type arguments of a generic function are determined only by the signature, so T
would be invalid in that context).
Nor can I change C
to become TypeVar('C', bound=X[T])
(can't use type arguments in that context either).
Nor can I use def g(cls: Callable[[], C[T]]) -> None
(type variables cannot be used with arguments).
So ???
is a type that mypy understands, but there's no way to actually refer to it.
Of course, the toy example above works without annotation (mypy simply infers type of x
) but if I need to make a list of those things, I'm out of luck:
def g(cls: Callable[[], C]) -> None:
x: List[???] = []
for i in range(10):
x.append(cls().f())