Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.as_completed

Iterates over tasks as they complete so an early result can be processed without waiting for slower siblings.

Version: Python 3.14; repository image, production runtime not attested

Syntax

asyncio.as_completed(aws, *, timeout=None)

Iterates over tasks as they complete so an early result can be processed without waiting for slower siblings.

Asynchronous iteration in Python 3.14 yields the original scheduled tasks when they were supplied as tasks. An explicit event controls completion order in this example.

Process results in completion order. Since 3.13 async iteration yields the supplied tasks/futures themselves, while plain iteration yields wrapper coroutines to await. A timeout raises TimeoutError without cancelling the remaining work. In the example fast completes first and the gate then lets slow finish.

import asyncio
async def main():
    loop = asyncio.get_running_loop()
    f = loop.create_future()
    f.set_result(3)
    assert [v async for v in asyncio.as_completed([f])] == [f]
    wrapper = next(iter(asyncio.as_completed([f])))
    assert wrapper is not f and await wrapper == 3
asyncio.run(main())

Examples

import asyncio
async def wait(gate):
    await gate.wait()
    return "slow"

async def main():
    gate = asyncio.Event()
    slow = asyncio.create_task(wait(gate))
    fast = asyncio.create_task(asyncio.sleep(0, result="fast"))
    async for task in asyncio.as_completed([slow, fast]):
        print(task is fast, task.result())
        gate.set()

asyncio.run(main())

Result

True fast
False slow

Process results in completion order. Since 3.13 async iteration yields the supplied tasks/futures themselves, while plain iteration yields wrapper coroutines to await. A timeout raises TimeoutError without cancelling the remaining work. In the example fast completes first and the gate then lets slow finish.

Sources