异步def函数的“屈服于”选项

2024-05-16 05:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个几乎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\u one\u fin\u instr\u hist\u data必须是一个协程,因为它是由异步函数调用的。 其签名如下:

async def fetch_one_fin_instr_hist_data(self, obj):

一切正常。 不幸的是@asyncio.coroutine已被弃用,因此我应该用async def关键字替换它。 async def不支持yield from

我尝试了以下方法:

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]”

有没有办法将协同程序转换为iterable? 或者更好的是,在这种情况下,的产量的替代方案是什么


Tags: keyinselfasyncioobjfordataasync
2条回答

正如dirn在评论中提到的,yieldawait取代:

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

虽然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])

相关问题 更多 >