Complete worked example
python
import asyncio
def inspect_example(names):
async def run():
started = 0
all_started = asyncio.Event()
cleanup = []
if not names:
all_started.set()
async def worker(name):
nonlocal started
started += 1
if started == len(names):
all_started.set()
try:
await asyncio.Event().wait()
finally:
cleanup.append(name)
async def fail():
await all_started.wait()
raise ValueError('controlled sibling failure')
failed = False
try:
async with asyncio.TaskGroup() as group:
for name in names:
group.create_task(worker(name))
group.create_task(fail())
except* ValueError:
failed = True
return {'closed': sorted(cleanup), 'failed': failed}
return asyncio.run(run())- Reasoning
- A shared counter and all_started event coordinate the failure task. With two names, both workers reach their waiting point before the failure raises ValueError. The task group cancels those waiting workers, their finally blocks append names and the matching exception-group handler records failure.