Skip to content

Need a way to refer to the type parameter of a generic class inside a generic function #3151

Closed
@pkch

Description

@pkch

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())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions