A timeout limits how long a caller waits and can cancel work inside its scope. Cleanup needs to survive cancellation.
Worked example
import asyncio
async def main():
try:
async with asyncio.timeout(0):
await asyncio.sleep(1)
except TimeoutError:
print('Timed out')
asyncio.run(main())Result
Timed outImplementation notes
A timed-out task can have already performed part of its work. Make retried operations safe if a cancelled attempt may have changed external state.
Try it yourself
Try a task shorter than the deadline and one that exceeds it.
Open the Python example →Editorial date May 22, 2026 · Published December 6, 2026