I’m trying to create a Mixin that assumes the child class has a certain variable that is of a generic type.
I use a Protocol to define that constraint on the mixin but mypy doesn’t seem to be able to resolve it.
Here is the most minimal version of my could I could get that reproduces the issue:
from abc import ABC, ABCMeta
from typing import Generic, Protocol, TypeVar
class MyOne:
def __init__(self) -> None:
pass
MyOneT = TypeVar("MyOneT", bound=MyOne)
class Foo(Generic[MyOneT], metaclass=ABCMeta):
def __init__(self, my_var: MyOneT) -> None:
self.my_var: MyOneT = my_var
Bar = Foo[MyOne]
class ChildBar(Bar, ABC):
pass
class HasMyVarProtocol(Protocol[MyOneT]):
my_var: MyOneT
class MyMixin(HasMyVarProtocol[MyOne]):
def __init__(self) -> None:
pass
class MyMainClass(ChildBar, MyMixin):
def __init__(self, my_var: MyOne) -> None:
super().__init__(my_var)
This produces the following error:
error: Definition of "my_var" in base class "Foo" is incompatible with definition in base class "HasMyVarProtocol" [misc]
class MyMainClass(ChildBar, MyMixin):
It seems mypy isn’t able to resolve that my_var
are of the same generic type.