Python 3.4+Async programmingfunction
asyncio.wait_for()
timeouts
Waits for an awaitable for at most the given number of seconds; on expiry it cancels it and raises TimeoutError.
Syntax
result = await asyncio.wait_for(aw, timeout)
Unlike wait(), wait_for cancels what it was waiting for and waits for the cancellation to finish, so it may return later than timeout if the task cleans up slowly. Since 3.11 it raises the built-in TimeoutError (asyncio.TimeoutError became an alias); earlier you had to catch asyncio.TimeoutError. timeout=None waits forever; for a block of several awaits async with asyncio.timeout() reads better.
Examples
# Python 3.11+
import asyncio
async def slow():
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print('отменена')
raise
async def main():
try:
await asyncio.wait_for(slow(), timeout=0.01)
except TimeoutError:
print('не успела')
asyncio.run(main()) # → отменена / не успела
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy