What is Python's async generators and async context managers?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Python codebase.
Previous
What is Python's decorator advanced patterns?
Next
What is Python's import system and __init__.py?