gpt4 book ai didi

python - 委托(delegate)给 python 3.6+ asyncio 协程中的生成器

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:30 25 4
gpt4 key购买 nike

在 python 3.3 中,我可以执行以下操作

def _gen():
for i in range(3):
yield i

def gen():
yield from _gen()

for i in gen():
print(i)

>>> 0
>>> 1
>>> 2

我可以在 python 3.6 asyncio 协程中做同样的事情吗? (警告,人为的例子)

async def _gen():
for i in range(3):
yield await get_num(i) # get_num is a coroutine

async def gen():
yield from _gen() # Syntax error!

for i in gen():
print(i)

我需要将 gen 定义为

async def gen():
async for i in _gen():
yield i

但似乎应该有一种方法可以委托(delegate)给另一个协程,就像我们可以使用 yield from

最佳答案

由于 described in PEP 525 的原因,Python 3.6 不支持

yield from :

While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.

yield from is also less critical for asynchronous generators, since there is no need provide a mechanism of implementing another coroutines protocol on top of coroutines. And to compose asynchronous generators a simple async for loop can be used:

async def g1():
yield 1
yield 2

async def g2():
async for v in g1():
yield v

关于python - 委托(delegate)给 python 3.6+ asyncio 协程中的生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49989861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com