CKTIS / Python
asyncio.gather
Spustí korutiny souběžně a po await poskytne seznam v pořadí argumentů.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
asyncio.gather(*aws, return_exceptions=False)Spustí korutiny souběžně a po await poskytne seznam v pořadí argumentů.
Ve výchozím nastavení předá první výjimku a ostatní úlohy pokračují. Zrušení čekajícího gather zruší nedokončené potomky.
Při return_exceptions=True obsadí výjimka vlastní pozici, proto se vypíše 5 a ValueError.
import asyncio
async def main():
gate = asyncio.Event()
slow = asyncio.create_task(gate.wait())
async def fail():
raise ValueError("bad")
try:
await asyncio.gather(slow, fail())
except ValueError:
assert not slow.done()
gate.set()
assert await slow is True
asyncio.run(main())
Příklady
import asyncio
async def fail():
raise ValueError("sample")
async def main():
results = await asyncio.gather(asyncio.sleep(0, result=5), fail(), return_exceptions=True)
print(results[0], type(results[1]).__name__)
asyncio.run(main())
Výsledek
5 ValueError
Při return_exceptions=True obsadí výjimka vlastní pozici, proto se vypíše 5 a ValueError.