Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Python: asyncio.gather vs TaskGroup — which should I use now?

clock icon

asked 2 months ago

message icon

1

eye icon

593

I have used asyncio.gather for years. Newer code keeps using TaskGroup. Is gather deprecated, or do they solve different problems?

1 Answer

gather isn't deprecated, but TaskGroup is the better default for concurrent work that should succeed or fail together.

The difference is what happens on failure. With gather, when one task raises, the others keep running unless you cancel them yourself — a common source of leaked tasks and confusing logs:

1async with asyncio.TaskGroup() as tg:
2 a = tg.create_task(fetch_user())
3 b = tg.create_task(fetch_orders())
4# both awaited; if either raises, the other is cancelled
1async with asyncio.TaskGroup() as tg:
2 a = tg.create_task(fetch_user())
3 b = tg.create_task(fetch_orders())
4# both awaited; if either raises, the other is cancelled

TaskGroup cancels siblings on the first failure and raises an ExceptionGroup covering everything that went wrong.

gather is still the right tool when you specifically want return_exceptions=True — "run all of these, tell me which ones failed, don't stop for any of them".

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions