Async Generator in Python
Level 5181 keystrokes
This defines an async generator using async def and yield. async for iterates over values yielded asynchronously.
Python code
# Import asyncio for async operations1import asyncio2 # Define async generator function3async def async_counter(n): # Loop from 0 to n-14 for i in range(n): # Wait 0.1 s without blocking, simulating async work5 await asyncio.sleep(0.1) # Yield value asynchronously6 yield i7 # Define main async function8async def main(): # Async for loop to iterate over async generator9 async for num in async_counter(5): # Print each yielded value10 print(num)11 # Run the async main function12asyncio.run(main())Output
0 1 2 3 4
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 8)× 8:× 4.× 3_× 2