What is Python's async generators and async context managers?
Answer
Async generators combine async functions and generators — they use async def and yield together. Example: async def paginated_data(url): page = 1; while True: data = await fetch(url, page=page); if not data: break; for item in data: yield item; page += 1. Consume with async for item in paginated_data(url). Async context managers implement __aenter__ and __aexit__ (both coroutines): async with aiofiles.open("file.txt") as f: content = await f.read(). Create with @asynccontextmanager: async def db_transaction(): async with pool.acquire() as conn: try: yield conn; await conn.commit(); except: await conn.rollback(). These patterns are essential for building efficient async data pipelines, streaming API responses, and resource management in async web applications.
Previous
What is Python's decorator advanced patterns?
Next
What is Python's import system and __init__.py?