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 operations
1import asyncio
2
# Define async generator function
3async def async_counter(n):
# Loop from 0 to n-1
4 for i in range(n):
# Wait 0.1 s without blocking, simulating async work
5 await asyncio.sleep(0.1)
# Yield value asynchronously
6 yield i
7
# Define main async function
8async def main():
# Async for loop to iterate over async generator
9 async for num in async_counter(5):
# Print each yielded value
10 print(num)
11
# Run the async main function
12asyncio.run(main())

Output

0
1
2
3
4
Practice typing this code

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

More Python examples at level 5

← Python typing practice