1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Coroutine function generic type alias

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024 às 23:12.

  1. Stack

    Stack Membro Participativo

    I'm trying to achieve a typing shorthand for coroutines just like basic callables like Callable[[..args..], ..return value..]

    My idea is to write something like that, but in the attempt, I cannot understand how TypeAlias would later match where the P, and where the RV...

    P = ParamSpec('P')
    RV = TypeVar('RV')

    CoroutineFunction: TypeAlias = Callable[P, Awaitable[RV]]


    Then, I want to use it as follows

    # this is just sample coroutine
    async def my_afunc(a: int, b: str) -> bool:
    return bool(a or b)

    # this is usage example
    def some_decorator(afunc: CoroutineFunction[[int, str], bool]):
    ...

    # this should handle type checking correctly,
    # and warn me if I change the return value type for my_afunc
    smth = some_decorator(my_afunc)



    I'm using python 3.11, but 3.12 ideas are also appreciable.

    Continue reading...

Compartilhe esta Página