【问题标题】:'yield from' alternative for async def function'yield from' 替代 async def 函数
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正如 dirn 在 cmets 中提到的,yield 被替换为 await

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-29
      • 2019-04-07
      • 2023-01-25
      • 2014-11-16
      • 2019-01-06
      • 2017-03-27
      • 1970-01-01
      • 2016-07-06
      相关资源
      最近更新 更多