【发布时间】:2021-09-30 23:13:00
【问题描述】:
在一个几乎 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 关键字替换它。
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]'
有没有办法将协程转换为可迭代的? 或者更好的是,在这种情况下,yield from 的替代方法是什么?
【问题讨论】:
-
yield from在该上下文中已替换为await。 -
“ fetch_one_fin_instr_hist_data 必须是协程,因为它是由异步函数调用的” 它会异步执行任何操作吗?如果不是,它不需要是协程。
-
好的,只需将
yield from替换为await即可!谢谢
标签: python python-asyncio coroutine iterable