Sub topic 3
Deadlines with `asyncio.timeout`
Assume Python 3.11 or newer, async/await, asyncio.run(), and basic try/except and context-manager syntax.
Deadlines with `asyncio.timeout`
asyncio.timeout() is an asynchronous context manager that gives code a deadline. When the deadline expires, it cancels the current task. Outside the context, that cancellation becomes TimeoutError.
import asyncio
async def main():
try:
async with asyncio.timeout(0.5):
await asyncio.sleep(2)
except TimeoutError:
print("operation timed out")
asyncio.run(main())Put the try block around the context manager. Catching TimeoutError inside the block does not work because the exception is raised after the context exits.
`asyncio.wait_for`
asyncio.wait_for(awaitable, timeout) limits one awaitable. Prefer it for a single operation. Prefer asyncio.timeout() when one deadline should cover several awaits or a larger block.
result = await asyncio.wait_for(fetch_data(), timeout=2)Both mechanisms cancel the operation when time runs out. Cancellation can take time if the operation must run cleanup before it finishes.
Timeouts around a task group
A timeout outside a TaskGroup gives all child tasks one shared deadline. The group cancels unfinished children before the timeout is reported.
async with asyncio.timeout(1.5):
async with asyncio.TaskGroup() as group:
for item in items:
group.create_task(process(item))Shielding selected work
asyncio.shield(task) prevents cancellation of the inner task when its outer wait is cancelled. The caller may stop waiting, but the task continues. Keep its task reference and await it later.
task = asyncio.create_task(save())
try:
await asyncio.wait_for(asyncio.shield(task), 0.1)
except TimeoutError:
result = await taskShield only work that must finish, such as a committed save. It does not protect the task from direct cancellation.
Bounding concurrency
An asyncio.Semaphore limits how many tasks enter a section at once.
limit = asyncio.Semaphore(10)
async def fetch(url):
async with limit:
return await request(url)Cancellation details
Task.cancelling() reports pending cancellation requests. Task.uncancel() removes one pending request and is mainly used internally by structured concurrency and timeout machinery. Application code should normally propagate CancelledError, not suppress it.
Graceful shutdown
On shutdown, cancel tracked tasks, let their finally blocks run, and await them. Signal handlers can set an asyncio.Event; the main task then performs this cleanup.
Exercise
Which construct should you choose for one awaitable, and which for a deadline covering several awaits?
Show answer
Use asyncio.wait_for for one awaitable and asyncio.timeout for a larger block.