[Python] How to type a generic callable in python

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to do something like this:

    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)


    But I get the following mypy error on my await process_command(my_command, my_command_handler) line

    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]


    Which I don't understand because MyCommand is a Command[int].

    How do I make mypy happy here?

    Continue reading...

Compartilhe esta Página