|
| 1 | +"""Manage a group of async tasks. |
| 2 | +
|
| 3 | +This is intended to mimic the behaviors of asyncio.TaskGroup released in Python 3.11. |
| 4 | +
|
| 5 | +- Docs: https://docs.python.org/3/library/asyncio-task.html#task-groups |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +from typing import Any, Coroutine |
| 10 | + |
| 11 | + |
| 12 | +class _TaskGroup: |
| 13 | + """Shim of asyncio.TaskGroup for use in Python 3.10. |
| 14 | +
|
| 15 | + Attributes: |
| 16 | + _tasks: List of tasks in group. |
| 17 | + """ |
| 18 | + |
| 19 | + _tasks: list[asyncio.Task] |
| 20 | + |
| 21 | + def create_task(self, coro: Coroutine[Any, Any, Any]) -> asyncio.Task: |
| 22 | + """Create an async task and add to group. |
| 23 | +
|
| 24 | + Returns: |
| 25 | + The created task. |
| 26 | + """ |
| 27 | + task = asyncio.create_task(coro) |
| 28 | + self._tasks.append(task) |
| 29 | + return task |
| 30 | + |
| 31 | + async def __aenter__(self) -> "_TaskGroup": |
| 32 | + """Setup self managed task group context.""" |
| 33 | + self._tasks = [] |
| 34 | + return self |
| 35 | + |
| 36 | + async def __aexit__(self, *_: Any) -> None: |
| 37 | + """Execute tasks in group. |
| 38 | +
|
| 39 | + The following execution rules are enforced: |
| 40 | + - The context stops executing all tasks if at least one task raises an Exception or the context is cancelled. |
| 41 | + - The context re-raises Exceptions to the caller. |
| 42 | + - The context re-raises CancelledErrors to the caller only if the context itself was cancelled. |
| 43 | + """ |
| 44 | + try: |
| 45 | + await asyncio.gather(*self._tasks) |
| 46 | + |
| 47 | + except (Exception, asyncio.CancelledError) as error: |
| 48 | + for task in self._tasks: |
| 49 | + task.cancel() |
| 50 | + |
| 51 | + await asyncio.gather(*self._tasks, return_exceptions=True) |
| 52 | + |
| 53 | + if not isinstance(error, asyncio.CancelledError): |
| 54 | + raise |
| 55 | + |
| 56 | + context_task = asyncio.current_task() |
| 57 | + if context_task and context_task.cancelling() > 0: # context itself was cancelled |
| 58 | + raise |
| 59 | + |
| 60 | + finally: |
| 61 | + self._tasks = [] |
0 commit comments