Run the coroutine synchronously - trying to accommodate as many edge cases as possible. 1. When called within a coroutine. 2. When called from ``python -m asyncio``, or iPython with %autoawait enabled, which means an event loop may already be running in the current
(
coroutine: Coroutine[Any, Any, ReturnType],
)
| 9 | |
| 10 | |
| 11 | def run_sync( |
| 12 | coroutine: Coroutine[Any, Any, ReturnType], |
| 13 | ) -> ReturnType: |
| 14 | """ |
| 15 | Run the coroutine synchronously - trying to accommodate as many edge cases |
| 16 | as possible. |
| 17 | 1. When called within a coroutine. |
| 18 | 2. When called from ``python -m asyncio``, or iPython with %autoawait |
| 19 | enabled, which means an event loop may already be running in the |
| 20 | current thread. |
| 21 | """ |
| 22 | try: |
| 23 | # We try this first, as in most situations this will work. |
| 24 | return asyncio.run(coroutine) |
| 25 | except RuntimeError: |
| 26 | # An event loop already exists. |
| 27 | with ThreadPoolExecutor(max_workers=1) as executor: |
| 28 | future: Future = executor.submit(asyncio.run, coroutine) |
| 29 | return future.result() |