Skip to the solution
HardBackend13 min read

How does TaskGroup handle cancellation and ExceptionGroup?

852 views

The problem

Question presented to candidate: "Inside async with asyncio.TaskGroup(), one child task raises. Walk me through exactly what happens next: to the other children, to the code in the async with body, and to the exception you finally see. Then: what if the whole thing is cancelled from outside, or wrapped in a timeout?"

What a strong answer should cover:

  • On the first child failure the group cancels every other running child and the parent task running the body, then waits for all of them, including their finally / cleanup code, before leaving the block.
  • The result is one ExceptionGroup("unhandled errors in a TaskGroup", [...]) holding every non-cancellation error (children and body); CancelledErrors of the cancelled children are not included. Handle it with except*.
  • The group cancels the parent with cancel() and undoes it with uncancel() in __aexit__, so its own cancellation turns into the group error, while a real outside cancellation still comes out as a plain CancelledError (and asyncio.timeout turns it into TimeoutError).
  • A child that swallows CancelledError breaks the contract: it keeps running cleanup or returns normally; always re-raise.
  • KeyboardInterrupt and SystemExit are treated specially (re-raised as-is, not grouped); nested groups stay nested.

Clarifying questions expected:

  • Should one failing child really stop the others, or are some children "best effort"?

Code / implementation expected: Optional โ€” a TaskGroup where one child fails and another prints when it is cancelled, caught with except*.

  • asyncio
  • exceptiongroup
  • cancellation

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

13 min read ยท 11 sections

Run the code

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

PythonA child fails: who gets cancelled, cleanup, and the group
PythonOutside cancellation, timeouts, a sentinel stop and swallowed cancels

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 123 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 nextHard

How do TypeAdapter, strict mode, and computed fields work in Pydantic v2?

Continue