Отключить ошибку типа аргумента mypy при использовании шаблона состоянияPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Отключить ошибку типа аргумента mypy при использовании шаблона состояния

Сообщение Anonymous »

Минимальный пример:

Код: Выделить всё

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
)
Мое решение «мечты», чтобы указать mypy, что тип события и тип обработчика «связаны» вместе.
Чего мне хотелось бы избежать, так это установки типа ввода моего события в каждом DataGathererVX как EventV1 | EventV2 и добавьте утверждение isinstance(event, EventVX) в начале каждого метода, так как моя цель — вызвать ошибки, когда эти методы вызываются с неправильным типом события.

Подробнее здесь: https://stackoverflow.com/questions/791 ... gy-pattern
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»