在一个几乎 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 的替代方案是什么?
最佳答案
虽然 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])
关于python - 异步 def 函数的“yield from”替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68505720/