What is Python's asyncio advanced patterns?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Python deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
Advanced asyncio patterns for production applications. Task management: task = asyncio.create_task(coro()) — runs concurrently; cancel with task.cancel(). Timeout: async with asyncio.timeout(5): await fetch() (Python 3.11+) or await asyncio.wait_for(coro(), timeout=5). Gather with errors: asyncio.gather(*tasks, return_exceptions=True) — returns exceptions as values instead of propagating. Semaphore (limit concurrency): sem = asyncio.Semaphore(10); async with sem: await fetch(). Queue: asyncio.Queue() for producer-consumer patterns. Synchronization: asyncio.Lock(), asyncio.Event(). Background tasks: asyncio.get_event_loop().call_later(5, callback). Running in executor: await loop.run_in_executor(None, blocking_function) — run blocking code in a thread pool without blocking the event loop. Always prefer async libraries (aiohttp over requests, asyncpg over psycopg2) in async code.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Python answers easy to follow.
Previous
What is Python's __init_subclass__ and class decorators?
Next
What is Python's __enter__ and __exit__ for custom context managers?