A generator can be iterated step by step by using the next() built-in function. For example:
def sync_gen(n):
"""Simple generator"""
for i in range(n):
yield i**2
sg = sync_gen(4)
print(next(sg)) # -> 0
print(next(sg)) # -> 1
print(next(sg)) # -> 4
Using next() on an asynchronous generator does not work:
import asyncio
async def async_gen(n):
for i in range(n):
yield i**2
async def main():
print("Async for:")
async for v in async_gen(4): # works as expected
print(v)
print("Async next:")
ag = async_gen(4)
v = await next(ag) # raises: TypeError: 'async_generator' object is not an iterator
print(v)
asyncio.run(main())
Does something like v = await async_next(ag) exist to obtain same behavior as with normal generators?