python-3.xgenericstypingtype-variables

Bound TypeVar on generic methods inside generic class


For some reason, this code lints up as a problem:

from typing import *
T = TypeVar("T", bound="Foo")
S = TypeVar("S")

class Foo(Generic[S]):
    @classmethod
    def func(cls: Type[T]) -> T:
        return cls()

Mypy linter sends me to the def func line, saying Unsupported type Type["T"]. This does not happen if Foo is not defined as a generic class.

Is this a bug? What am I doing wrong?

I'm using S for different methods, and I wish to use T and Type[T] later on inside subclasses of Foo.


Solution

  • I believe this is a bug in mypy. Unfortunately, the best workaround for now is to just add a # type: ignore annotation to that line, perhaps along with a link to the relevant issue. Later, you can check if that warning has been fixed by running mypy with the --warn-unused-ignores flag.