Sub topic 10
Deadlines with asyncio.timeout
This chapter assumes you know async/await, asyncio.create_task, and how cancellation raises CancelledError inside a task. You need Python 3.11 or newer, because asyncio.timeout was added in 3.11.
The basic pattern
asyncio.timeout(delay) is an async context manager. It sets a deadline for the code in its block. If the block is still running when the deadline passes, the manager cancels the current task. When the block exits, it converts that cancellation into a TimeoutError.
import asyncio
async def main():
try:
async with asyncio.timeout(0.5):
await asyncio.sleep(2)
except TimeoutError:
print("timed out")
asyncio.run(main())The try/except goes outside the async with. The error is raised only when the block exits, so a handler inside the block never sees it.
What happens at the deadline
The timeout uses ordinary cancellation. Nothing is killed from outside.
Three consequences follow:
- Cancellation happens only at an
await. Blocking code such astime.sleep(5)or a long CPU loop is never interrupted. - Cleanup in
finallyblocks runs beforeTimeoutErrorappears. - The timeout only works inside a task, because it cancels the current task.
asyncio.run(main())already gives you one.
Changing the deadline
The object returned by async with lets you move the deadline or check whether it fired. Deadlines are absolute times on the event loop's clock, which you read with loop.time().
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() + 0.2)
await asyncio.sleep(0.5)
except TimeoutError:
print("expired:", cm.expired())
asyncio.run(main())The new deadline falls 0.2 seconds after the first sleep, so the second sleep is cut short and expired() returns True. Passing None to asyncio.timeout creates a timeout with no deadline, which you can set later with reschedule. asyncio.timeout_at(when) takes an absolute time directly.
Common errors
- Handler in the wrong place. Putting
except TimeoutErrorinside theasync withnever fires. - Blocking calls. A synchronous call inside the block delays cancellation until the next
await, so the deadline is late. - A broad
except Exception. In Python 3.8+,CancelledErrorderives fromBaseException, soexcept Exceptiondoes not catch it. A bareexcept:orexcept BaseException:does catch it, and you should avoid both. - Treating
TimeoutErroras specific to your block. If code inside the block raises its ownTimeoutError, such as a socket timeout, your handler catches that too. Usecm.expired()to tell the two cases apart.
Why prefer it
One asyncio.timeout can cover several awaits, so the budget applies to the whole block instead of to each call. It also nests, and the inner and outer deadlines are tracked separately. The next chapter compares it with asyncio.wait_for, which bounds a single awaitable.
Exercise
A coroutine runs async with asyncio.timeout(1): and inside it does try: await asyncio.sleep(5) except asyncio.CancelledError: print("cleanup") without re-raising. What happens after the deadline, and how do you fix it?
Show answer
"cleanup" is printed, but the block then ends normally and no TimeoutError is raised, because the handler swallowed the CancelledError the timeout needed. Add raise after the cleanup, or use a finally block for cleanup, so the exception reaches the end of the block.