Skip to content

.tip

· one of the small things

asyncio.TaskGroup, not gather, for a group of tasks

When one task raises, gather keeps the others running and the exception shows up late. A task group cancels the rest on the first failure and raises the errors together.

async with asyncio.TaskGroup() as tg:
    a = tg.create_task(fetch(url_a))
    b = tg.create_task(fetch(url_b))
print(a.result(), b.result())

It needs Python 3.11 or later. This is structured concurrency: nothing outlives the block that started it.

pythonconcurrency