Timeouts and cancellation

A server that never answers would make your program wait forever. In real code, every network call needs a timeout.

asyncio.timeout(seconds) is a context manager (Python 3.11+). If the code inside takes too long, the task is cancelled and you get TimeoutError:

async with asyncio.timeout(0.5):
    data = await fetch(url)

asyncio.wait_for(coro, timeout) does the same for one coroutine, and works on older versions too.

Cancellation works by raising CancelledError inside the task at the await where it was waiting. So try/finally blocks still run, and you can clean up. CancelledError is a BaseException, not an Exception, so a broad except Exception doesn't swallow it by accident. If you catch it yourself, re-raise it.

Run it. Then raise the timeout above 0.1 and see the slow call succeed.