Python 3.11+Async programmingfunction
asyncio.timeout()
timeouts
An asynchronous context manager that times out a whole block: if the block does not finish within delay seconds it is interrupted and TimeoutError escapes.
Syntax
async with asyncio.timeout(delay) as cm: ...
Inside the block a timeout arrives as CancelledError, and only on leaving async with does the manager turn it into TimeoutError, so catch it outside the block, not inside. The deadline can be moved on the fly with cm.reschedule(); timeout(None) means "no deadline yet". Do not swallow CancelledError inside the block or the timeout will not fire. Added in 3.11; before that there was only wait_for. The manager is an asyncio.Timeout object; its constructor Timeout(when) takes an absolute loop time (loop.time()), not a delay: Timeout(5) is a moment long gone.
Examples
import asyncio
async def main():
try:
async with asyncio.timeout(0.01) as cm:
await asyncio.sleep(0.01)
await asyncio.sleep(1)
except TimeoutError:
print('блок не уложился', cm.expired()) # → блок не уложился True
asyncio.run(main())
import asyncio
async def main():
async with asyncio.timeout(None) as cm:
cm.reschedule(asyncio.get_running_loop().time() + 1)
await asyncio.sleep(0.01)
print(cm.expired()) # → False
asyncio.run(main())
import asyncio
async def main():
loop = asyncio.get_running_loop()
async with asyncio.Timeout(loop.time() + 1) as cm: # абсолютное время цикла
await asyncio.sleep(0.01)
print(cm.expired()) # → False
asyncio.run(main())
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy