CKTIS / Python
asyncio.wait_for
Awaits one operation with a timeout and returns its result on success.
Version: Python 3.14; repository image, production runtime not attested
Syntax
await asyncio.wait_for(aw, timeout)Awaits one operation with a timeout and returns its result on success.
When the timeout expires the inner task is normally cancelled before TimeoutError reaches the caller.
Await one operation, using seconds for the deadline or None to wait indefinitely. On timeout request cancellation and wait for the operation to finish cancelling, so cleanup can exceed the nominal time. If cancellation propagates, raise TimeoutError; if the operation catches cancellation and returns a value, return that value. The example observes cancellation at zero and 9 on success.
import asyncio
async def main():
start = asyncio.Event()
async def recover():
start.set()
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
return 7
t = asyncio.create_task(recover())
await start.wait()
assert await asyncio.wait_for(t, 0) == 7
assert await asyncio.wait_for(asyncio.sleep(0, result=9), None) == 9
asyncio.run(main())
Examples
import asyncio
async def main():
task = asyncio.create_task(asyncio.Event().wait())
try:
await asyncio.wait_for(task, timeout=0)
except TimeoutError:
print(task.cancelled())
print(await asyncio.wait_for(asyncio.sleep(0, result=9), timeout=5))
asyncio.run(main())
Result
True 9
Await one operation, using seconds for the deadline or None to wait indefinitely. On timeout request cancellation and wait for the operation to finish cancelling, so cleanup can exceed the nominal time. If cancellation propagates, raise TimeoutError; if the operation catches cancellation and returns a value, return that value. The example observes cancellation at zero and 9 on success.