Я хочу определить подклассы, реализующие эту азбуку и возвращающие экземпляры конкретные подклассы. Однако mypy не допускает этого и утверждает, что у меня несовместимые типы возвращаемых значений.
Следующий пример демонстрирует, чего я пытаюсь достичь.
Код: Выделить всё
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"]
Код: Выделить всё
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]
Подробнее здесь: https://stackoverflow.com/questions/790 ... en-methods