Is asyncio.sleep() necessary when yielding?

rmlibre at riseup.net rmlibre at riseup.net
Tue Jan 28 19:27:58 EST 2020


(Sorry about the double submission)

I'm trying to figure out how the event loop handles switching tasks
inside of an async generator, and consequently, the constraints on its
calling code. For example:

> async def gen():
>     for number in range(10 ** 7):
>         yield number
>
> 
> async def consumer():
>     numbers = []
>     async for number in gen():
>         numbers.append(number)
>     return numbers
>

The gist of my question is: will consumer block the event loop if
iterating over an async generator like the example gen()? In so
requiring an await asyncio.sleep(0) call? Or, does the yield statement
in an async generator cause the event loop to continue doing the rounds
across its scheduled tasks without awaiting asyncio.sleep(0)?


More information about the Python-list mailing list