Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

What is the difference between `asyncio.gather` and `TaskGroup`?

AdvancedConceptConcurrency: threads, processes & asyncio
Answer
  • gather(*aws) runs awaitables concurrently and returns results in order. By default the first exception propagates but the other tasks keep running unattended; return_exceptions=True returns exceptions as values.
  • asyncio.TaskGroup (3.11+) is structured concurrency: if any task fails, the others are cancelled, and errors are raised together as an ExceptionGroup (handled with except*).
async with asyncio.TaskGroup() as tg:
    t1 = tg.create_task(fetch("a"))
    t2 = tg.create_task(fetch("b"))
print(t1.result(), t2.result())

Use TaskGroup when partial results are useless; gather with return_exceptions=True for "probe everything, report failures".

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio