Sub topic 11
asyncio.wait_for and when to prefer timeout
This chapter assumes Python 3.11 or newer. It also assumes you know asyncio.create_task, CancelledError, and the asyncio.timeout context manager from the previous chapter.
What wait_for does
asyncio.wait_for(aw, timeout) runs one awaitable and gives it a time limit in seconds. If the awaitable finishes in time, you get its result. If not, wait_for cancels it and raises TimeoutError.
import asyncio
async def fetch():
try:
await asyncio.sleep(2)
return "data"
finally:
print("fetch: cleanup")
async def main():
try:
result = await asyncio.wait_for(fetch(), timeout=0.5)
print(result)
except TimeoutError:
print("fetch took too long")
asyncio.run(main())The output is fetch: cleanup followed by fetch took too long. The finally block runs first because wait_for waits for the cancelled awaitable to finish before it raises.
Where wait_for falls short
wait_for wraps exactly one awaitable. A deadline that covers several steps would need a separate call for each step. Each call restarts the clock, so the total time can exceed what you intended.
asyncio.timeout fixes this. It sets one deadline for a whole block:
import asyncio
async def step(name, delay):
await asyncio.sleep(delay)
print(f"{name} done")
async def main():
try:
async with asyncio.timeout(1.0):
await step("connect", 0.4)
await step("download", 0.4)
await step("parse", 0.4)
except TimeoutError:
print("pipeline exceeded 1.0 s")
asyncio.run(main())connect and download finish. parse would end at 1.2 seconds, so the block is cancelled at 1.0 and the program prints pipeline exceeded 1.0 s.
Choosing between them
| Situation | Prefer |
|---|---|
| One awaitable, one limit | `wait_for` or `timeout` |
| Several awaits sharing a deadline | `timeout` |
| Deadline around a `TaskGroup` | `timeout` |
| Deadline that may move, or must be inspected | `timeout` |
timeout is the better default. The object returned by asyncio.timeout has reschedule() and expired() methods, and it works with any block of code.
Use wait_for when you want a one-line limit on a single call. Since Python 3.12, wait_for is built on timeout internally, so the cancellation behaviour is the same.
Common errors
timeout=Nonemeans no limit. A variable that is accidentallyNonesilently disables the deadline.wait_forwaits for the cancelled awaitable to finish. If the inner code catchesCancelledErrorand keeps going,wait_forblocks and the deadline has no effect.- The timeout cancels the awaitable. Work that must survive the deadline needs
asyncio.shield.
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())Here wait_for cancels only the shield wrapper. The save task keeps running, and the caller can still await it.
Exercise
A function awaits three network calls in a row and must finish within 5 seconds in total. Why is wrapping each call in wait_for(..., timeout=5) the wrong approach, and what should you use?
Show answer
Each wait_for starts its own 5-second clock, so the three calls could take up to 15 seconds in total. Use one async with asyncio.timeout(5): around all three awaits so they share a single deadline.