Код: Выделить всё
from typing import overload, TypeVar, Generic
class EventV1:
pass
class EventV2:
pass
class DataGathererV1:
def process(self, event: EventV1):
pass
def process2(self, event: EventV1):
pass
class DataGathererV2:
def process(self, event: EventV2):
pass
def process2(self, event: EventV2):
pass
class Dispatcher:
def __init__(self):
self.worker_v1: DataGathererV1 = DataGathererV1()
self.worker_v2: DataGathererV2 = DataGathererV2()
def dispatch(self, event: EventV1 | EventV2):
handler: DataGathererV1 | DataGathererV2 = self.worker_v1 if isinstance(event, EventV1) else self.worker_v2
handler.process(event)
# Common logic
handler.process2(event)
# Common logic
handler.process(event)
# etc...
Mypy выдает следующие ошибки, и я не знаю, как правильно набирать код, чтобы избежать подобных ошибок.
Код: Выделить всё
example.py:36: error: Argument 1 to "process" of "DataGathererV1" has incompatible type "EventV1 | EventV2"; expected "EventV1" [arg-type]
example.py:36: error: Argument 1 to "process" of "DataGathererV2" has incompatible type "EventV1 | EventV2"; expected "EventV2" [arg-type]
example.py:40: error: Argument 1 to "process2" of "DataGathererV1" has incompatible type "EventV1 | EventV2"; expected "EventV1" [arg-type]
example.py:40: error: Argument 1 to "process2" of "DataGathererV2" has incompatible type "EventV1 | EventV2"; expected "EventV2" [arg-type]
example.py:44: error: Argument 1 to "process" of "DataGathererV1" has incompatible type "EventV1 | EventV2"; expected "EventV1" [arg-type]
example.py:44: error: Argument 1 to "process" of "DataGathererV2" has incompatible type "EventV1 | EventV2"; expected "EventV2" [arg-type]
Код: Выделить всё
@overload
def __handler(self, event: EventV1) -> tuple[DataGathererV1, EventV1]:
...
@overload
def __handler(self, event: EventV2) -> tuple[DataGathererV2, EventV2]:
...
def __handler(self, event: EventV1 | EventV2) -> tuple[DataGathererV1 | DataGathererV2, EventV1 | EventV2]:
return (
self.worker_v1 if isinstance(event, EventV1) else self.worker_v2,
event
)
Чего мне хотелось бы избежать, так это установки типа ввода моего события в каждом DataGathererVX как EventV1 | EventV2 и добавьте утверждение isinstance(event, EventVX) в начале каждого метода, так как моя цель — вызвать ошибки, когда эти методы вызываются с неправильным типом события.
Подробнее здесь: https://stackoverflow.com/questions/791 ... gy-pattern