等待任务时键入提示

时间:2020-07-10 11:44:52

标签: python python-asyncio

请考虑以下两个功能:

@asyncio.coroutine
async def get_int() -> int:
    await asyncio.sleep(0.5)
    return 5


@asyncio.coroutine
async def get_str() -> str:
    await asyncio.sleep(0.5)
    return "str"

我想成为第一个完成的协程及其结果,所以我正在等待FIRST_COMPLETED

    next_int_coro = asyncio.Task(get_int())
    next_str_coro = asyncio.Task(get_str())

    done, pending = await asyncio.wait([next_int_coro, next_str_coro],
                                       return_when=asyncio.FIRST_COMPLETED)

    if next_int_coro in done:
        some_int = await next_int_coro # type hint for some_int = Any :(
        print(f"int : {some_int}")

    elif next_str_coro in done:
        some_str = await next_str_coro # type hint for some_str = Any :(
        print(f"str : {some_str}")
    else:
        print("unexpected coroutine ended")

问题是,我想在处理任务结果时有类型提示。相反,我得到Any

如果不直接将协程包装在Task中,我可以直接得到类型提示:

next_int_coro = get_int()
some_int = await next_int_coro # some_int is hinted to be an int

但是在那种情况下,我无法确定哪个协程首先结束(检查协程是否属于“ if elif elsedone集的Future最终在{ {1}}。

我如何才能两全其美?我的意思是得到等待结果的类型提示,并且能够知道哪个协程首先结束。

0 个答案:

没有答案