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 support1import asyncio2 # async def with yield makes async_range an async generator3async 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 delay5 await asyncio.sleep(delay) # yield produces values one at a time asynchronously6 yield i7 # async def async_filter filters an async iterable8async def async_filter(predicate, async_iterable): # async for iterates over async generator9 async for item in async_iterable: # Only yield items that pass the predicate10 if predicate(item): # yield the matching item11 yield item12 # async def main is the main coroutine13async def main(): # results list to collect filtered values14 results = [] # Consume async_range(1, 10) filtered to even numbers15 async for num in async_filter(lambda x: x % 2 == 0, async_range(1, 10, 0.01)): # Append each even number to results16 results.append(num) # Print the collected even numbers17 print(f"Even numbers: {results}")18 # asyncio.run starts the event loop and runs main19asyncio.run(main())Output
Even numbers: [2, 4, 6, 8]
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