首页 > 解决方案 > Await Doesn't Work with Coroutine Assigned to Variable?

问题描述

Why in Python (3.6) does

chunk = await evt_loop.run_in_executor(io_exec, arc.read, chunk_size)

work exactly as expected but

read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size)
chunk = await read_ftr

throws AssertionError("yield from wasn't used with future",) on the second line, and how do I get it to work?

The following is the snippet of code I'm trying to run. Fusing the three read_ftr lines together to get the first single-line implementation works, while the way it is below throws that assertion error at "chunk = await read_ftr".

read_ftr: aio.Future = None
hash_ftr: aio.Future = None
chunk = None

with open(arc_path, "rb") as arc:
    while arc_offs < arc_size:
        chunk_size = min(arc_size - arc_offs, max_chunk_size)

        if read_ftr:
            chunk = await read_ftr
        read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size)
        arc_offs += chunk_size

        if not chunk:
            continue

        if hash_ftr:
            await hash_ftr
        hash_ftr = hasher.async_update(chunk)

if hash_ftr:
    await hash_ftr
await hasher.async_digest()

标签: pythonpython-3.xpython-asyncio

解决方案


当你像你一样声明一个变量时,你foo_var = coroutine(args)实际上是在调用函数并将其结果应用于变量。要将函数作为变量传递,请执行此操作foo_var = coroutine,然后在foo_var(args)任何时候在函数旁边添加括号时调用它,它将尝试调用并运行该函数(即使它是协程/异步函数)


推荐阅读