Skip to the solution
MediumBackend11 min read

What is asyncio.TaskGroup and why does it replace gather?

732 views

The problem

Question presented to candidate: "You need to call three services concurrently from an async handler. Most older code would use asyncio.gather for that. Python 3.11 added asyncio.TaskGroup. What is it, and why do people say it should replace gather?"

What a strong answer should cover:

  • What it is: an async context manager (async with asyncio.TaskGroup() as tg:) whose tg.create_task() starts child tasks; leaving the block waits for every child β€” the idea called structured concurrency (added in Python 3.11).
  • The failure behaviour: when one child raises, TaskGroup cancels the other children and the body, waits for them, then raises an ExceptionGroup with every error; plain gather raises the first error and leaves the siblings running unattended.
  • Errors are not lost: gather silently drops the 2nd, 3rd... errors (unless return_exceptions=True, which turns errors into values you must check); TaskGroup keeps them all, handled with except*.
  • Results: gather returns a list in argument order; with TaskGroup you keep the Task objects and call .result() after the block.
  • Honest trade-off: TaskGroup is not a drop-in replacement β€” gather with return_exceptions=True is still the right tool when you want partial results; TaskGroup needs 3.11+.

Clarifying questions expected:

  • If one of the calls fails, do you want the others cancelled, or do you want whatever results succeeded?
  • Which Python version does the service run on (TaskGroup needs 3.11+)?

Code / implementation expected: Optional β€” the same three calls written with gather and with TaskGroup, and what happens when one fails.

  • asyncio
  • taskgroup

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythongather leaves orphans; TaskGroup cancels siblings
PythonSeveral failures: gather, return_exceptions and TaskGroup

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 70 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does a for loop work under the hood?

Continue