Однако я столкнулся с проблемой при реализации Handler. Код работает с посредником, но когда я пытаюсь передать запрос обработчику, я получаю следующую ошибку:
Код: Выделить всё
line 40: Diagnostics:
1. Method "handle" overrides class "Handler" in an incompatible manner
Parameter 2 type mismatch: base parameter is type "QUERY[T@handle]", override parameter is type "StringQuery"
"QUERY[T@handle]" is not assignable to "StringQuery" [reportIncompatibleMethodOverride]
line 46: Diagnostics:
1. Method "handle" overrides class "Handler" in an incompatible manner
Parameter 2 type mismatch: base parameter is type "QUERY[T@handle]", override parameter is type "IntQuery"
"QUERY[T@handle]" is not assignable to "IntQuery" [reportIncompatibleMethodOverride]
Код: Выделить всё
from typing import Protocol, TypeVar, Generic
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class QUERY(Generic[T]): ...
@dataclass
class Mediator:
@staticmethod
def execute_query(query: QUERY[T]) -> T: ...
@dataclass
class Handler(Protocol):
def handle(self, query: QUERY[T]) -> T: ...
@dataclass
class StringQuery(QUERY[str]):
any_data: str
limit: int
@dataclass
class IntQuery(QUERY[int]):
another_data: bool
@dataclass
class StringHandler(Handler):
# I expect that it will automatically understand that
# it needs to return str here, and if I don’t return str in
# the function itself, for example, mypy will show an error.
def handle(self, query: StringQuery):
return 1
@dataclass
class IntHandler(Handler):
# I expect that it will automatically understand that
# it needs to return int here, and if I don’t return int in
# the function itself, for example, mypy will show an error.
def handle(self, query: IntQuery):
return "s"
mediator = Mediator()
string_query = StringQuery("SELECT * FROM users")
result_str = mediator.execute_query(string_query) # works as expected, result is of type str
int_query = IntQuery("SELECT COUNT(*) FROM users")
result_int = mediator.execute_query(int_query) # works as expected, result is of type int
Может ли кто-нибудь объяснить, почему Mediator работает, а Handler — нет? Почему возникает несоответствие типов и как сделать метод handle в Handler совместимым с QUERY и его подклассами, такими как StringQuery и IntQuery?
Подробнее здесь: https://stackoverflow.com/questions/797 ... ble-method