Async for loop

Async for loop with async for syntax are only with asynchronous generators or iterators.

async def async_gen(n):
    for i in range(1, n):
        yield i
        await asyncio.sleep(i)
 
 
@with_time
async def main():
    task = asyncio.create_task(timeout(2))
 
    async for item in async_gen(5):
        print(item)
 
    await task
 
if __name__ == "__main__":
    asyncio.run(main())

It gives the result as follows,

1
before timeout 2
2
3
after timeout 2
4
total time elapsed:  10.004251718521118