Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
Bharel Avatar asked Feb 18 '26 16:02

Bharel


1 Answers

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.

like image 155
Michael0x2a Avatar answered Feb 20 '26 18:02

Michael0x2a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!