Execute multiple asynchronous coroutines in parallel, sharing the current context between them.
(*coros)
| 39 | |
| 40 | |
| 41 | async def _run_parallel(*coros): |
| 42 | """ |
| 43 | Execute multiple asynchronous coroutines in parallel, |
| 44 | sharing the current context between them. |
| 45 | """ |
| 46 | context = contextvars.copy_context() |
| 47 | |
| 48 | if len(coros) == 0: |
| 49 | return [] |
| 50 | |
| 51 | async def run(i, coro): |
| 52 | results[i] = await coro |
| 53 | |
| 54 | try: |
| 55 | async with asyncio.TaskGroup() as tg: |
| 56 | results = [None] * len(coros) |
| 57 | for i, coro in enumerate(coros): |
| 58 | tg.create_task(run(i, coro), context=context) |
| 59 | return results |
| 60 | except BaseExceptionGroup as exception_group: |
| 61 | if len(exception_group.exceptions) == 1: |
| 62 | raise exception_group.exceptions[0] |
| 63 | raise |
| 64 | finally: |
| 65 | _restore_context(context=context) |
| 66 | |
| 67 | |
| 68 | class Signal: |
no test coverage detected