Sub topic 11
asyncio.wait_for and when to prefer timeout
This chapter assumes you know Python 3.11 or newer, async/await, try/finally, and how asyncio.run starts a program. You should also have read the earlier chapters on cancellation and on asyncio.timeout. asyncio.wait_for is the older way to put a time limit on an awaitable. It is still common in existing code, and it is still a good fit in one specific case.
What wait_for does
asyncio.wait_for(aw, timeout) awaits one awaitable and returns its result. If the awaitable has not finished after timeout seconds, wait_for cancels it and raises TimeoutError.
import asyncio
async def lookup():
await asyncio.sleep(2)
return "value"
async def main():
try:
result = await asyncio.wait_for(lookup(), timeout=0.5)
print(result)
except TimeoutError:
print("lookup took too long")
asyncio.run(main())Three details matter in practice:
- The
timeoutis relative, in seconds. PassingNonemeans no limit, and the call then simply awaits the argument. - Since Python 3.11,
asyncio.TimeoutErroris the same class as the built-inTimeoutError. Older code that catchesasyncio.TimeoutErrorstill works. New code can catchTimeoutError. wait_forcancels the awaitable on timeout, so the awaitable must handleCancelledErrorcorrectly. Put cleanup infinallyand do not swallow the error, as covered in the cancellation chapters.
How it differs from asyncio.timeout
Both tools cancel work when a deadline passes, and both end in TimeoutError. They differ in what they cover.
| Aspect | `asyncio.wait_for` | `asyncio.timeout` |
|---|---|---|
| Form | A function call that awaits one awaitable | An async context manager around a block |
| Scope | Exactly one awaitable | Any number of awaits and statements |
| Budget | A fresh relative timeout on every call | One deadline shared by everything in the block |
| Changing the deadline | Not possible | `reschedule()` and `expired()` on the context manager |
| Absolute deadline | Not supported | `asyncio.timeout_at(when)` |
| Python version | All asyncio versions | 3.11 and newer |
The shared budget is the difference that most often matters. Each wait_for call restarts the clock, so a sequence of calls can run far longer than any single timeout suggests.
import asyncio
async def step(name, delay):
await asyncio.sleep(delay)
print(name, "done")
async def with_wait_for():
await asyncio.wait_for(step("a", 0.8), timeout=1)
await asyncio.wait_for(step("b", 0.8), timeout=1)
print("wait_for: 1.6 s in total, no timeout")
async def with_timeout():
try:
async with asyncio.timeout(1):
await step("a", 0.8)
await step("b", 0.8)
except TimeoutError:
print("timeout: the shared 1 s budget ran out during step b")
async def main():
await with_wait_for()
await with_timeout()
asyncio.run(main())In with_wait_for, each step fits inside its own one-second limit, so nothing times out even though the whole operation took 1.6 seconds. In with_timeout, the second step is cancelled about 0.2 seconds in, because the block has only one second in total.
Adjusting a deadline in flight
The context manager returned by asyncio.timeout lets you move the deadline while the block runs. reschedule takes an absolute time on the event loop's clock, which you read with loop.time(). expired() tells you afterwards whether the deadline was what stopped the block.
import asyncio
async def main():
loop = asyncio.get_running_loop()
try:
async with asyncio.timeout(1) as cm:
await asyncio.sleep(0.5)
cm.reschedule(loop.time() + 2)
await asyncio.sleep(1.5)
print("finished after the extended deadline")
except TimeoutError:
print("timed out")
print("expired:", cm.expired())
asyncio.run(main())wait_for offers no equivalent. If you need to extend a limit when you see progress, such as when data keeps arriving, use timeout.
How wait_for behaves internally
The implementation changed between Python versions, and the change explains some old advice you may still read.
- Up to Python 3.11,
wait_forwrapped the awaitable in a task, started a timer, and on expiry cancelled that task and waited for it to finish cancelling. - From Python 3.12,
wait_foris built onasyncio.timeout. It awaits a coroutine directly inside a timeout block instead of creating an extra task.
In both versions, wait_for waits for the cancelled awaitable to finish its cleanup before it raises TimeoutError. This means a slow finally block delays the error. It also means an awaitable that ignores cancellation can keep wait_for from returning at all, so the time limit is not a hard guarantee.
import asyncio
async def stubborn():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("stubborn: ignoring cancellation, finishing cleanup first")
await asyncio.sleep(1)
raise
async def main():
loop = asyncio.get_running_loop()
start = loop.time()
try:
await asyncio.wait_for(stubborn(), timeout=0.2)
except TimeoutError:
print(f"TimeoutError after {loop.time() - start:.1f} s")
asyncio.run(main())The error arrives after roughly 1.2 seconds, not 0.2, because the cleanup runs to completion first. If stubborn caught CancelledError and did not re-raise it, the behavior would be worse: the awaitable would finish normally and the timeout would be undermined.
Using shield with wait_for
Sometimes a timeout should stop you waiting without stopping the work. Wrap the work in a task, shield it, and give the shielded wrapper to wait_for. The timeout cancels only the wrapper, and the inner task keeps running.
import asyncio
async def save():
await asyncio.sleep(0.3)
print("save finished")
return "saved"
async def main():
inner = asyncio.create_task(save())
try:
await asyncio.wait_for(asyncio.shield(inner), timeout=0.1)
except TimeoutError:
print("stopped waiting, but save is still running")
print(await inner)
asyncio.run(main())Keep a reference to inner, as in the fire-and-forget chapter. Without it, nothing owns the task once you stop waiting. Use this pattern sparingly, because it deliberately leaves a task running outside the scope that started it.
Choosing between them
Prefer asyncio.timeout in new code for these reasons:
- It covers a block, so one deadline can bound several steps.
- It composes with
TaskGroup: a timeout around the group cancels every child (see the next chapter). - It supports
reschedule,expired, andtimeout_at. - It nests cleanly. An inner timeout fires first if its deadline is earlier, and an outer one fires if it is earlier.
Prefer wait_for when:
- You must support Python versions before 3.11.
- You are bounding a single call and want it on one line, for example
await asyncio.wait_for(queue.get(), timeout=5). - You are editing code that already uses it. Replacing working
wait_forcalls withtimeoutblocks is not required.
Common mistakes
- Assuming one
timeoutvalue bounds a whole function. Callingwait_forseveral times gives each call its own budget. Use oneasync with asyncio.timeout(...)for a total limit. - Catching
Exceptionaround a timed section and hidingTimeoutError. Since 3.8,CancelledErrorderives fromBaseException, butTimeoutErroris an ordinaryException. A broadexcept Exceptionwill swallow it. - Catching
CancelledErrorinside the timed code and not re-raising. The timeout cannot work if cancellation never propagates. - Expecting a hard real-time limit. Both tools only request cancellation. Code that blocks the event loop with synchronous work, such as
time.sleepor a long computation, delays the timer as well. - Relying on
wait_fortiming out on an awaitable that ignores cancellation. As shown above, the call waits for it.
Exercise
A function awaits wait_for(fetch_a(), 2) and then wait_for(fetch_b(), 2). Each call takes 1.5 seconds. The caller wants the whole function to fail if it takes more than 2 seconds in total. Does the current code do that, and how do you fix it?
Show answer
No. Each call has its own 2-second budget and finishes in 1.5 seconds, so the function succeeds after 3 seconds. Wrap both awaits in one block: async with asyncio.timeout(2): await fetch_a(); await fetch_b(). The second fetch is then cancelled about 0.5 seconds in, and TimeoutError is raised outside the block. Catch it there.
Exercise
You call await asyncio.wait_for(job(), timeout=1). The job coroutine catches CancelledError, sleeps 3 seconds for cleanup, then re-raises it. After how many seconds does the caller see TimeoutError, and why?
Show answer
After about 4 seconds. wait_for cancels job at 1 second and then waits for job to finish its cleanup, which takes 3 more seconds. Only then does it raise TimeoutError.