I have an abstract base class that defines a function to return a list with elements inheriting from a specific class.
I want to define subclasses that implements this ABC, and returns instances of specific subclasses. However, mypy won’t allow it, and claims that I have incompatible return types.
The following example highlight what I’m trying to achieve.
from abc import ABC, abstractmethod
from typing import override
class Base:
pass
class Derived(Base):
pass
class Abstract(ABC):
@abstractmethod
def foo(self) -> list[Base]: ...
# This should pass because foo returns a list of Derived, which is a subclass of Base
class ConcreteShouldPass(Abstract):
@override
def foo(self) -> list[Derived]:
return [Derived()]
# This should fail because foo returns a list of str, not Base
class ConcreteShouldFail(Abstract):
@override
def foo(self) -> list[str]:
return ["foo"]
However, both ConcreteShouldPass
and ConcreteShouldFail
fails mypy with the following errors:
foo.py:20: error: Return type "list[Derived]" of "foo" incompatible with return type "list[Base]" in supertype "Abstract" [override]
foo.py:26: error: Return type "list[str]" of "foo" incompatible with return type "list[Base]" in supertype "Abstract" [override]
How can I get the implementation in ConcreteShouldPass
to succeed, and the implementation in ConcreteShouldFail
to fail type checking?
2