Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

asyncio.as_completed

Processa resultados por ordem de conclusão.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

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

Processa resultados por ordem de conclusão.

Desde 3.13 async for fornece as tarefas ou Future originais e for normal fornece corrotinas intermediárias para await. A expiração gera TimeoutError sem cancelar o trabalho restante.

No exemplo fast termina primeiro e o sinal desbloqueia depois slow.

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())

Exemplos

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())

Resultado

True fast
False slow

No exemplo fast termina primeiro e o sinal desbloqueia depois slow.

Fontes