InterviewHubPRO
Section Overview
Q29

Question 29 of 65

Part 3: Asynchronous Programming & Concurrency (26 - 40)

45%
Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)

`asyncio.gather()` vs `asyncio.TaskGroup()`:

In Simple Words:

  • asyncio.gather(): Runs tasks concurrently. If one fails, others keep running by default unless cancelled manually.
  • asyncio.TaskGroup() (Python 3.11+): Implements Structured Concurrency. If one task fails with an unhandled exception, all remaining child tasks are automatically cancelled immediately!
python
# Modern structured concurrency with TaskGroup:
async def run_pipeline():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(fetch_user(1))
        task2 = tg.create_task(fetch_orders(1))
    # Both tasks are guaranteed completed or cancelled when exiting context block
    print(task1.result(), task2.result())