Code

Expeditions with TaskGroup

asyncio.TaskGroup (Python 3.11+) is the modern, safe way to run a bunch of tasks together. This is called structured concurrency:

async with asyncio.TaskGroup() as tg:
    t1 = tg.create_task(fetch_map("Ember"))
    t2 = tg.create_task(fetch_map("Frost"))
# leaving the block waits for every task
print(t1.result(), t2.result())

What makes it safe:

  • The async with block doesn't end until every task is done. No task is left running and forgotten.
  • If any task raises, the group cancels the others and raises all the errors together as an ExceptionGroup.

You can catch errors from inside a group with except*. It matches exceptions of that type inside the group:

try:
    async with asyncio.TaskGroup() as tg:
        ...
except* ValueError as group:
    for err in group.exceptions:
        print("problem:", err)

Assignment

Write run_expedition(crews). crews is a dict like {"Ash": 0.02} that maps crew name to delay.

  1. Inside a TaskGroup, create one task for each crew with explore(crew, delay).
  2. After the group finishes, return a dict that maps each crew to its task's .result().
  3. Don't catch the errors. If a crew gets lost, the ExceptionGroup should reach the caller, and the other crews should be cancelled.