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=Truereturns exceptions as values.asyncio.TaskGroup(3.11+) is structured concurrency: if any task fails, the others are cancelled, and errors are raised together as anExceptionGroup(handled withexcept*).
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".
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?Intermediate