
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 withblock 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.
- Inside a
TaskGroup, create one task for each crew withexplore(crew, delay). - After the group finishes, return a dict that maps each crew to its
task's
.result(). - Don't catch the errors. If a crew gets lost, the
ExceptionGroupshould reach the caller, and the other crews should be cancelled.
Write run_expedition(crews). crews is a dict like {"Ash": 0.02}
that maps crew name to delay.
- Inside a
TaskGroup, create one task for each crew withexplore(crew, delay). - After the group finishes, return a dict that maps each crew to its
task's
.result(). - Don't catch the errors. If a crew gets lost, the
ExceptionGroupshould reach the caller, and the other crews should be cancelled.
main.py Python sleeping
Press Run to try your code, then Check to test it.