Content · Programming · Python

Python asyncio.gather() vs TaskGroup: Error Handling

gather and TaskGroup both coordinate concurrent awaitables, but their failure semantics differ.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

gather and TaskGroup both coordinate concurrent awaitables, but their failure semantics differ.

Understanding the Concept


gather and TaskGroup both coordinate concurrent awaitables, but their failure semantics differ. TaskGroup cancels and waits for siblings on a child failure and reports grouped exceptions.

Prefer TaskGroup when child task lifetimes should be bounded by one lexical scope.

How the event loop makes progress


When a coroutine reaches await, it may suspend so another ready Task can execute. This scheduling is cooperative: blocking operations that do not yield hold up every coroutine sharing the event loop. Assign ownership of background tasks, put timeouts around operations that may wait, and release resources on cancellation.

An async function does not automatically use several CPU cores. Use async-compatible I/O for waiting tasks and executors or separate processes for blocking or CPU-heavy work when appropriate.

Worked Example


Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.

import asyncio

async def good():
    await asyncio.sleep(0)
    return "ok"

async def main():
    print(await asyncio.gather(good(), good()))
    async with asyncio.TaskGroup() as group:
        tasks = [group.create_task(good()) for _ in range(2)]
    print([task.result() for task in tasks])

asyncio.run(main())

Walkthrough: What Each Part Does


  • The central operation is asyncio.gather(good(), good()). Read its actual arguments: those values determine what is tested, logged, measured or scheduled. Then locate the line that inspects its result or handles a failure.
  • The imports make asyncio available. These are standard-library building blocks unless the example explicitly names an external tool.
  • The definition good, main creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
  • The with or async with scope controls lifetime. Setup takes place on entry, and cleanup runs on exit even when an exception interrupts the body.
  • Each await is a suspension point. When the awaited operation is not ready, the loop can schedule other tasks instead of blocking the entire thread.

This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.

Example Output


['ok', 'ok']
['ok', 'ok']

The output above was captured by running the example in the available Python environment. The order of concurrent events, durations and platform-dependent values can legitimately differ on your computer.

Important Behavior and Edge Cases


Expecting gather’s default first-error propagation to automatically cancel all siblings like TaskGroup.

Prefer TaskGroup when child task lifetimes should be bounded by one lexical scope.

Practice Exercise


Run one successful and one failing task under both constructs, handling outstanding tasks explicitly.

Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.

Further reading: official documentation and API reference.

Common Beginner Mistakes


  • Expecting gather’s default first-error propagation to automatically cancel all siblings like TaskGroup.
  • Calling a blocking function inside the event loop, or creating tasks without awaiting, cancelling or owning them.

Key Takeaways


  • gather and TaskGroup both coordinate concurrent awaitables, but their failure semantics differ.
  • Prefer TaskGroup when child task lifetimes should be bounded by one lexical scope.
  • Practice: Run one successful and one failing task under both constructs, handling outstanding tasks explicitly.
Share this resourceSend this page to someone who may find it useful.