Gathering Results

Gathering Results in Python: Imagine you are shopping for a party. You need: 1. Drinks from the supermarket (10 mins). 2. Cake from the bakery (5 mins). 3.

Concept Explanation

Imagine you are shopping for a party. You need:

  1. Drinks from the supermarket (10 mins).
  2. Cake from the bakery (5 mins).
  3. Balloons from the party store (5 mins).

If you do these one-by-one, it takes 20 minutes. But if you have three friends, you can ask them to do it "concurrently." You all start at the same time, and the whole trip only takes 10 minutes (the time of the longest task).

asyncio.gather() is how you send your "friends" to do work. You give it a list of coroutines, and it returns all their results back to you in a single list, in the exact order you requested.


Syntax or Core Structure

Using Gather

asyncio.gather() takes multiple coroutines (or tasks) separated by commas.

import asyncio

async def fetch_price(item):
    await asyncio.sleep(1)
    return f"{item}: $10"

async def main():
    # Run three requests at once
    results = await asyncio.gather(
        fetch_price("Apple"),
        fetch_price("Orange"),
        fetch_price("Banana")
    )
    
    print(results) # ["Apple: $10", "Orange: $10", "Banana: $10"]

asyncio.run(main())

Code Example #1 (Basic)

Handling a dynamic list of tasks.

import asyncio

async def task(n):
    await asyncio.sleep(n)
    return n * 10

async def main():
    nums = [1, 2, 3]
    
    # Create the list of coroutines
    coros = [task(n) for n in nums]
    
    # Use * to unpack the list into gather
    results = await asyncio.gather(*coros)
    
    print(f"Results: {results}")

asyncio.run(main())

Code Example #2 (Intermediate)

Handling Exceptions without crashing the whole group.

import asyncio

async def success():
    return "Great!"

async def failure():
    await asyncio.sleep(1)
    raise ValueError("Something went wrong!")

async def main():
    # return_exceptions=True prevents one error from stopping the others
    results = await asyncio.gather(
        success(),
        failure(),
        return_exceptions=True
    )
    
    print(f"Results: {results}") 
    # ['Great!', ValueError('Something went wrong!')]

asyncio.run(main())

Real World Example

Dashboard Data Loader: Imagine a website dashboard that needs to load "User Stats," "Recent Orders," and "Notification Count" all at once.

import asyncio

async def get_stats():
    await asyncio.sleep(1.5)
    return {"logins": 42}

async def get_orders():
    await asyncio.sleep(1.0)
    return ["Order 1", "Order 2"]

async def get_alerts():
    await asyncio.sleep(0.5)
    return 3

async def main():
    print("Loading Dashboard...")
    
    # Fetch all data concurrently
    stats, orders, alerts = await asyncio.gather(
        get_stats(),
        get_orders(),
        get_alerts()
    )
    
    print(f"Stats: {stats}")
    print(f"Orders: {len(orders)}")
    print(f"New Alerts: {alerts}")

asyncio.run(main())

Common Mistakes

  1. Forgetting to Unpack: If you have a list of tasks t = [task1, task2], you cannot use asyncio.gather(t). You MUST use asyncio.gather(*t).
  2. One Failure Kills All: By default, if one task in gather crashes, the whole await stops and raises that error (though other tasks keep running in the background). Use return_exceptions=True to get error objects back instead.
  3. Order Confusion: Gather returns results in the order you submitted them, not the order they finished. This is helpful for keeping data organized.

Best Practices

  • Batch Large Groups: If you have 10,000 tasks, don't use gather on all of them at once. It might overwhelm the system. Use a "Semaphore" to limit concurrency (e.g., only 50 at a time).
  • Group Related Tasks: Use gather for tasks that depend on each other or contribute to the same final result.
  • Use TaskGroups: In Python 3.11+, use asyncio.TaskGroup as a more modern, safer alternative to gather for handling groups of tasks.

Practice Exercises

  1. The Fast Five: Create 5 tasks with various asyncio.sleep times (1 to 5 seconds). Use gather to run them and verify they all finish in 5 seconds total.
  2. Safety Net: Create three tasks where the middle one raises an Exception. Use return_exceptions=True and print the results list.
  3. Data Unpacker: Write three tasks that return your First Name, Last Name, and Age. Use gather to get these and print them in a single formatted sentence.