Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate to a generator in python 3.6+ asyncio coroutine

In python 3.3 I can do the following

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

def gen():
    yield from _gen()

for i in gen():
    print(i)

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

Can I do the same within a python 3.6 asyncio coroutine? (Warning, contrived example)

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)

I need to define gen as

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

But it seems there should be a way to delegate to the other coroutine as we could with yield from

like image 572
shane Avatar asked Nov 20 '25 03:11

shane


1 Answers

yield from is not supported in Python 3.6 due to the reasons described in PEP 525:

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
like image 99
Mikhail Gerasimov Avatar answered Nov 22 '25 18:11

Mikhail Gerasimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!