python - 异步 def 函数的“yield from”替代方案

标签 python python-asyncio coroutine iterable

在一个几乎 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/

相关文章:

python - 合并两个具有重叠索引的数据框,保留左侧数据框中的列值

python - 如何使用python快速发送消息到azure队列存储?

python - 将嵌入式 python asyncio 集成到 boost::asio 事件循环中

python - 使用 pySmartDL 并行下载 - python 多进程

python - 使用 bulkloader 从 Google App Engine 下载数据时出错

python - 如何使用 SOCKS 代理向 aiohttp 发出请求?

c# - 在 unity3d 中运行时结束协程

python - 从基于生成器的协程转换为 native 协程

python - 根据条件从数据帧创建 python 列表

python asyncio双向通信硬件控制