首页 > 解决方案 > 'yield from' 替代 async def 函数

问题描述

在一个几乎 100% 异步的类中,我需要以同步(顺序)方式执行一些代码(当前是协程)。所以我创建了这个函数:

@asyncio.coroutine
def execute_sequential(self, doo):
    for key in doo:
        yield from self.fetch_one_fin_instr_hist_data(doo[key])

我用这些命令执行它:

tasks = [self.execute_sequential(doo)]
await asyncio.gather(*tasks)

fetch_one_fin_instr_hist_data必须是协程,因为它是由异步函数调用的它具有以下签名:

async def fetch_one_fin_instr_hist_data(self, obj):

一切正常。不幸的@asyncio.coroutine是,不推荐使用,所以我应该用async def关键字替换它。yield fromasync def支持。

我尝试了以下方法:

async def execute_sequential(self, doo):
    for key in doo:
        for obj in self.fetch_one_fin_instr_hist_data(doo[key]):
            yield obj

但在线

for obj in self.fetch_one_fin_instr_hist_data(doo[key]):

我得到错误:

预期类型 'collections.Iterable',得到了 'Coroutine[Any, Any, None]'

有没有办法将协程转换为可迭代的?或者更好的是,在这种情况下,什么可以替代产量?

标签: pythonpython-asynciocoroutineiterable

解决方案


虽然yield from对于创建生成器仍然有效,但此特定内容已被await关键字替换。

@asyncio.coroutine
def execute_sequential(self, doo):
    for key in doo:
        yield from self.fetch_one_fin_instr_hist_data(doo[key])

现在应该是

async def execute_sequential(self, doo):
    for key in doo:
        await self.fetch_one_fin_instr_hist_data(doo[key])

推荐阅读