CKTIS / Python
asyncio.as_completed
Traite les résultats dans l’ordre d’achèvement.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
asyncio.as_completed(aws, *, timeout=None)Traite les résultats dans l’ordre d’achèvement.
Depuis 3.13 async for fournit les tâches ou Future d’origine, tandis que for ordinaire fournit des coroutines intermédiaires à attendre. Une expiration lève TimeoutError sans annuler le travail restant.
Dans l’exemple fast termine en premier puis le signal libère 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())
Exemples
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())
Résultat
True fast False slow
Dans l’exemple fast termine en premier puis le signal libère slow.