Introduction
Async generators yield values asynchronously, useful for streaming data and processing sequences.
Async Generator
async def count_up_to(n):
for i in range(n):
yield i
await asyncio.sleep(0.5)
async def main():
async for value in count_up_to(5):
print(value)
asyncio.run(main())
Async Comprehensions
async def fetch_values():
for i in range(5):
yield i * 2
await asyncio.sleep(0.1)
async def main():
# List comprehension
result = [x async for x in fetch_values()]
# Set comprehension
unique = {x async for x in fetch_values()}
Async Iteration
class AsyncCounter:
def __init__(self, n):
self.n = n
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.n:
raise StopAsyncIteration
value = self.current
self.current += 1
await asyncio.sleep(0.1)
return value
async def main():
async for i in AsyncCounter(5):
print(i)
Practice Problems
- Create async generator for paginated API
- Process items with async comprehensions
- Build async iterator for WebSocket messages
- Combine async generators with gather
- Implement async generator with filtering