In my app I have resources that will create tasks that:
are created by asynchronous events
are independent from each other (i.e. cancellation of one task should not affect the others)
have a finite life span shorter than the life span of the resource
should have errors handled immediately upon completion
As a result the set of running (not done) child tasks is dynamically changing.
asyncio has different mechanisms for handling multiple (or groups of) tasks (i.e. TaskGroup, gather, wait) but I find they don't fit well in this scenario because:
TaskGroupdoes not work well here because of2.above.gatherandwaitdo not work well here because they would get really mad if I changed the set of tasks they are awaiting (are iterating over)
My solution is:
each resource will store child tasks in a
TaskRegistrywhen a child task completes the errors are handled and the child task is removed from the registry (via
done_callback)when a resource task is cancelled all child tasks in
TaskRegistryare cancelled and awaited.
Sample code shown below, and it works well, I'm just wondering if all of this is necessary or if there is a better way to do this (perhaps using some built-in asyncio tools that I may not be aware of).
Note: in the sample code the resource calls are all done at the same time but in a real situation they will be driven by asynchronous events.
import sys
import asyncio
import logging
from typing import Coroutine
from functools import partial
logging.basicConfig(level = logging.DEBUG, stream = sys.stdout, format = '%(asctime)s | %(levelname)7s | %(taskName)s | %(message)s')
logger = logging.getLogger(__name__)
type TaskName = str
type TaskRegistry = dict[TaskName, asyncio.Task]
def task_done_callback(task: asyncio.Task, registry: TaskRegistry):
logger.info(f"task done callback - {task.get_name()}")
try:
exception = task.exception()
except asyncio.CancelledError:
logger.info(f'task cancelled - {task.get_name()}')
else:
if exception:
logger.info(f"error in task - {exception} - {task.get_name()}")
logger.info(f"task finished - {task.get_name()}")
registry.pop(task.get_name())
def create_child_task(coro: Coroutine, registry: TaskRegistry, task_name: TaskName = None) -> asyncio.Task:
task = asyncio.create_task(coro)
if task_name is not None:
task.set_name(task_name)
task.add_done_callback(partial(task_done_callback, registry=registry))
registry[task.get_name()] = task
return task
async def cancel_child_tasks(registry: TaskRegistry):
for task in registry.values():
if task.cancel():
logger.warning(f'cancelling child task - {task.get_name()}')
try:
await task
except Exception as e:
logger.exception(f"exception in child task - {e} - {task.get_name()}")
except asyncio.CancelledError:
logger.info(f"child task cancelled - {task.get_name()}")
class Resource():
def __init__(self, name: str):
self.name = name
self.child_tasks: TaskRegistry = {}
async def run_coro(self):
try:
logger.info('resource running')
counter = 0
while True:
await asyncio.sleep(1)
counter += 1
if counter == 4: self.child_tasks['child task 3'].cancel()
except Exception as e:
logger.exception(f'uncaught exception in resource - {e}')
except asyncio.CancelledError:
logger.info('resource cancelled')
raise
finally:
await cancel_child_tasks(self.child_tasks)
logger.info('resource stopped')
async def do_something(self, index: int, duration: int):
try:
logger.info(f'do something {index} started')
await asyncio.sleep(duration)
except asyncio.CancelledError:
logger.info(f'do something {index} cancelled')
raise
else:
logger.info(f'do something {index} finished')
def use_resource(self, index: int, duration: int):
return create_child_task(self.do_something(index, duration), self.child_tasks, task_name= f"{self.name} - child task {index}")
async def main():
try:
tasks: TaskRegistry = {}
resource = Resource('Some Resource')
create_child_task(resource.run_coro(), tasks, 'Some Resource Task')
resource.use_resource(1, 1) ### pretend these are called by asynchronous events
resource.use_resource(2, 2)
resource.use_resource(3, 6)
resource.use_resource(4, 7)
counter = 0
while True:
await asyncio.sleep(1)
counter += 1
logger.debug(f"main counter: {counter}")
except Exception as e:
logger.exception(f'uncaught exception in main - {e}')
except asyncio.CancelledError:
logger.info(f'main cancelled')
finally:
await cancel_child_tasks(tasks)
logger.info(f'main finished')
if __name__ == '__main__':
asyncio.run(main())
Sample output:
2026-08-15 16:36:35,950 | DEBUG | None | Using selector: EpollSelector
2026-08-15 16:36:35,951 | INFO | Some Resource Task | resource running
2026-08-15 16:36:35,951 | INFO | Some Resource - child task 1 | do something 1 started
2026-08-15 16:36:35,951 | INFO | Some Resource - child task 2 | do something 2 started
2026-08-15 16:36:35,951 | INFO | Some Resource - child task 3 | do something 3 started
2026-08-15 16:36:35,951 | INFO | Some Resource - child task 4 | do something 4 started
2026-08-15 16:36:36,952 | DEBUG | Task-1 | main counter: 1
2026-08-15 16:36:36,953 | INFO | Some Resource - child task 1 | do something 1 finished
2026-08-15 16:36:36,953 | INFO | None | task done callback - Some Resource - child task 1
2026-08-15 16:36:36,953 | INFO | None | task finished - Some Resource - child task 1
2026-08-15 16:36:37,953 | INFO | Some Resource - child task 2 | do something 2 finished
2026-08-15 16:36:37,953 | DEBUG | Task-1 | main counter: 2
2026-08-15 16:36:37,953 | INFO | None | task done callback - Some Resource - child task 2
2026-08-15 16:36:37,953 | INFO | None | task finished - Some Resource - child task 2
^C2026-08-15 16:36:38,590 | INFO | Task-1 | main cancelled
2026-08-15 16:36:38,590 | WARNING | Task-1 | cancelling child task - Some Resource Task
2026-08-15 16:36:38,590 | INFO | Some Resource Task | resource cancelled
2026-08-15 16:36:38,590 | WARNING | Some Resource Task | cancelling child task - Some Resource - child task 3
2026-08-15 16:36:38,590 | INFO | Some Resource - child task 3 | do something 3 cancelled
2026-08-15 16:36:38,590 | INFO | None | task done callback - Some Resource - child task 3
2026-08-15 16:36:38,591 | INFO | None | task cancelled - Some Resource - child task 3
2026-08-15 16:36:38,591 | INFO | Some Resource Task | child task cancelled - Some Resource - child task 3
2026-08-15 16:36:38,591 | WARNING | Some Resource Task | cancelling child task - Some Resource - child task 4
2026-08-15 16:36:38,591 | INFO | Some Resource - child task 4 | do something 4 cancelled
2026-08-15 16:36:38,591 | INFO | None | task done callback - Some Resource - child task 4
2026-08-15 16:36:38,591 | INFO | None | task cancelled - Some Resource - child task 4
2026-08-15 16:36:38,591 | INFO | Some Resource Task | child task cancelled - Some Resource - child task 4
2026-08-15 16:36:38,591 | INFO | Some Resource Task | resource stopped
2026-08-15 16:36:38,591 | INFO | None | task done callback - Some Resource Task
2026-08-15 16:36:38,591 | INFO | None | task cancelled - Some Resource Task
2026-08-15 16:36:38,591 | INFO | Task-1 | child task cancelled - Some Resource Task
2026-08-15 16:36:38,591 | INFO | Task-1 | main finished