CKTIS / Python
asyncio.wait
Waits for a collection of tasks and returns separate sets of finished and pending tasks.
Version: Python 3.14; repository image, production runtime not attested
Syntax
await asyncio.wait(aws, *, timeout=None, return_when=asyncio.ALL_COMPLETED)Waits for a collection of tasks and returns separate sets of finished and pending tasks.
A timeout leaves pending tasks running. The caller is responsible for eventually completing or cancelling them.
Supply a nonempty collection of tasks or futures; bare coroutine objects are rejected. return_when selects the first completion, the first exception, or all completions. A timeout returns the done and pending sets without raising TimeoutError or cancelling pending tasks. In the example one is already done, and the gated task stays pending until explicitly released.
import asyncio
async def main():
loop = asyncio.get_running_loop()
a, b = loop.create_future(), loop.create_future()
a.set_result(2)
done, pending = await asyncio.wait([a, b], return_when=asyncio.FIRST_COMPLETED)
assert done == {a} and pending == {b} and not b.cancelled()
b.cancel()
try:
await asyncio.wait([])
except ValueError:
pass
else:
raise AssertionError
asyncio.run(main())
Examples
import asyncio
async def main():
gate = asyncio.Event()
pending_task = asyncio.create_task(gate.wait())
finished = asyncio.create_task(asyncio.sleep(0, result=5))
await finished
done, pending = await asyncio.wait([finished, pending_task], timeout=0)
print(len(done), len(pending), pending_task.cancelled())
gate.set()
await pending_task
asyncio.run(main())
Result
1 1 False
Supply a nonempty collection of tasks or futures; bare coroutine objects are rejected. return_when selects the first completion, the first exception, or all completions. A timeout returns the done and pending sets without raising TimeoutError or cancelling pending tasks. In the example one is already done, and the gated task stays pending until explicitly released.