I have the following code that replicates an error that I have in my original code:
from typing import Generic, TypeVar, ClassVar, Type
from abc import ABC, abstractmethod
T = TypeVar("T")
class Formatter(ABC, Generic[T]):
@staticmethod
@abstractmethod
def format(x: T) -> T:
...
class MyFormatter(Formatter[T]):
@staticmethod
def format(x: T) -> T:
return x
class FormattableClass(ABC, Generic[T]):
formatter: ClassVar[Type[Formatter]]
def __init__(self, x: T) -> None:
self.x: T = x
class SpecificFormattableClass(FormattableClass[T]):
formatter = MyFormatter
def __init__(self, x: T):
self.x = self.formatter.format(x)
Mypy shows the following error in the last line
Incompatible types in assignment (expression has type "T", variable has type "T")
How should I procede to solve it then?
I know it may be from the fact that mypy cannot know that "T" in the Formatter class is the same T as the FormattableClass generic. A possible solution I came up was simply do the following:
class FormattableClass(ABC, Generic[T]):
- formatter: ClassVar[Type[Formatter]]
+ formatter: ClassVar[Type[Formatter[T]]]
def __init__(self, x: T) -> None:
self.x: T = x
But mypy complains about another error
ClassVar cannot contain type variables