Код: Выделить всё
from collections.abc import Callable, Coroutine
from typing import Any, Generic, TypeVar
CRT = TypeVar("CRT", bound=Any)
class Command(Generic[CRT]): pass
CommandHandler = Callable[[Command[CRT]], Coroutine[Any, Any, CRT]]
class MyCommand(Command[int]): pass
async def my_command_handler(command: MyCommand) -> int:
return 42
async def process_command(command: Command[CRT], handler: CommandHandler[CRT]) -> CRT:
return await handler(command)
async def main() -> None:
my_command = MyCommand()
await process_command(my_command, my_command_handler)
Код: Выделить всё
Argument 2 to "process_command" has incompatible type "Callable[[MyCommand], Coroutine[Any, Any, int]]"; expected "Callable[[Command[int]], Coroutine[Any, Any, int]]"Mypyarg-type
(function) def my_command_handler(command: MyCommand) -> CoroutineType[Any, Any, int]
Как мне сделать Mypy счастливым? Класс и убедитесь, что обработчик принимает экземпляр команды в качестве параметра и возвращает правильный результат, определенный командой.
Код: Выделить всё
async def my_command_handler(command: Command[int]) -> int:
if not isinstance(command, MyCommand):
raise TypeError("Expected MyCommand")
return 42
Подробнее здесь: https://stackoverflow.com/questions/796 ... -in-python