Async Generator in Python

Level 5448 keystrokes

This chains two async generators (async def with yield): one produces numbers, the other filters them, and 'async for' consumes the even ones.

Python code

# Import asyncio for async/await support
1import asyncio
2
# async def with yield makes async_range an async generator
3async def async_range(start: int, stop: int, delay: float = 0.1):
# Loop over start..stop-1 like a regular range()
4 for i in range(start, stop):
# await asyncio.sleep simulates async delay
5 await asyncio.sleep(delay)
# yield produces values one at a time asynchronously
6 yield i
7
# async def async_filter filters an async iterable
8async def async_filter(predicate, async_iterable):
# async for iterates over async generator
9 async for item in async_iterable:
# Only yield items that pass the predicate
10 if predicate(item):
# yield the matching item
11 yield item
12
# async def main is the main coroutine
13async def main():
# results list to collect filtered values
14 results = []
# Consume async_range(1, 10) filtered to even numbers
15 async for num in async_filter(lambda x: x % 2 == 0, async_range(1, 10, 0.01)):
# Append each even number to results
16 results.append(num)
# Print the collected even numbers
17 print(f"Even numbers: {results}")
18
# asyncio.run starts the event loop and runs main
19asyncio.run(main())

Output

Even numbers: [2, 4, 6, 8]
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.

  • :× 12
  • (× 12
  • )× 12
  • ,× 7
  • _× 6
  • .× 5
  • =× 4
  • "× 2
  • [× 1
  • ]× 1

More Python examples at level 5

← Python typing practice