What is Python's asyncio advanced patterns?
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.
Previous
What is Python's __init_subclass__ and class decorators?
Next
What is Python's __enter__ and __exit__ for custom context managers?