Sub topic 10
Setting timeouts
This chapter assumes you can write coroutines, start tasks, and know that cancelling a task raises CancelledError inside it. The examples need Python 3.11 or later.
Why timeouts matter
A network call can wait forever if the other side never answers. Without a time limit, one stuck await can hold up a whole program. A timeout sets a maximum wait and stops the work when the limit passes.
asyncio.timeout
asyncio.timeout(seconds) is an async context manager. If the block runs past the limit, asyncio cancels the current task. The context manager then turns that cancellation into a TimeoutError when the block exits.
import asyncio
async def slow():
await asyncio.sleep(5)
return "finished"
async def main():
try:
async with asyncio.timeout(1):
print(await slow())
except TimeoutError:
print("timed out")
asyncio.run(main())This prints timed out after about one second. The except goes outside the async with, because the TimeoutError is raised as the block exits.
The limit covers everything inside the block, not a single await. This makes it a good fit for a group of tasks:
import asyncio
async def fetch(n):
await asyncio.sleep(0.5)
return n * 2
async def main():
async with asyncio.timeout(2):
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(1))
t2 = tg.create_task(fetch(2))
print(t1.result(), t2.result())
asyncio.run(main())If the two-second limit passed first, the TaskGroup would cancel its children and the timeout would raise TimeoutError.
asyncio.wait_for
asyncio.wait_for(awaitable, timeout) wraps a single awaitable. It returns the result, or cancels the awaitable and raises TimeoutError.
import asyncio
async def slow():
await asyncio.sleep(5)
async def main():
try:
await asyncio.wait_for(slow(), timeout=1)
except TimeoutError:
print("timed out")
asyncio.run(main())Use wait_for for one call. Use asyncio.timeout when one limit should cover several steps.
| Feature | `asyncio.timeout` | `asyncio.wait_for` |
|---|---|---|
| Form | `async with` block | Function call |
| Covers | Many awaits | One awaitable |
| Limit can change | Yes, with `reschedule` | No |
| Raises on expiry | `TimeoutError` | `TimeoutError` |
What happens on expiry
sequenceDiagramThe diagram below shows the order of events.
Common errors
- Swallowing
CancelledError. A timeout works by cancellation. If your code catchesCancelledErrorand does not re-raise it, the timeout cannot do its job. Always re-raise after cleanup. - Blocking calls. A call such as
time.sleepnever reaches an await, so the loop cannot cancel it. The timeout fires late or not at all. Move blocking code toasyncio.to_thread. - Catching the error in the wrong place. Putting
tryinside theasync withmisses theTimeoutError. - Expecting cleanup to be free. Cancellation runs your
finallyblocks, and the timeout only finishes after they complete.
Exercise
A coroutine wraps async with asyncio.timeout(1): around a task that catches asyncio.CancelledError, prints a message, and does not re-raise. What goes wrong?
Show answer
The timeout cancels the task, but the task swallows the cancellation. The block can then keep running past the limit, and the timeout does not raise TimeoutError as expected. Re-raise CancelledError after cleanup.
Exercise
You need one two-second limit across three sequential awaits. Do you use wait_for or asyncio.timeout?
Show answer
Use asyncio.timeout(2) around all three awaits. wait_for limits only one awaitable, so each call would get its own two-second limit.