⚡ Concurrency & Parallelism
asyncio timeouts & cancellation
Bound how long a coroutine may run; clean up on cancel.
Always bound network calls with a timeout. Modern asyncio.timeout() (3.11+) is the cleanest way; on older Pythons use asyncio.wait_for.
import asyncio
async def slow():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
# cleanup: close sockets, release resources, then re-raise
print("cancelled, cleaning up")
raise
async def main():
try:
async with asyncio.timeout(0.05): # 50 ms budget
await slow()
except TimeoutError:
print("timed out")
await main()
**Patterns**
asyncio.wait_for(coro, timeout=...)— same idea, returns the result.task.cancel()raisesCancelledErrorinside the coroutine. Re-raise after cleanup.asyncio.shield(coro)— protect a critical section from outer cancellation.asyncio.TaskGroup(3.11+) — structured concurrency; cancels siblings on failure.