CKTIS / Python
asyncio.gather
Executa corrotinas em concorrência e após await fornece uma lista pela ordem dos argumentos.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
asyncio.gather(*aws, return_exceptions=False)Executa corrotinas em concorrência e após await fornece uma lista pela ordem dos argumentos.
Por predefinição propaga a primeira exceção e as outras tarefas continuam. Cancelar um gather pendente cancela os filhos por concluir.
Com return_exceptions=True a exceção ocupa a sua posição, daí 5 e 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())
Exemplos
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())
Resultado
5 ValueError
Com return_exceptions=True a exceção ocupa a sua posição, daí 5 e ValueError.