Skip to main content
 首页 » 编程设计

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

2024年09月07日9cloudgamer

在 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