|
1 | 1 | from __future__ import annotations as _annotations |
2 | 2 |
|
3 | 3 | import asyncio |
| 4 | +import sys |
4 | 5 | import types |
| 6 | +from collections.abc import Coroutine |
5 | 7 | from functools import partial |
6 | 8 | from typing import Any, Callable, TypeVar |
7 | 9 |
|
|
10 | 12 | from typing_inspection.introspection import is_union_origin |
11 | 13 |
|
12 | 14 |
|
13 | | -def get_event_loop(): |
14 | | - try: |
15 | | - event_loop = asyncio.get_event_loop() |
16 | | - except RuntimeError: |
17 | | - event_loop = asyncio.new_event_loop() |
18 | | - asyncio.set_event_loop(event_loop) |
19 | | - return event_loop |
20 | | - |
21 | | - |
22 | 15 | def get_union_args(tp: Any) -> tuple[Any, ...]: |
23 | 16 | """Extract the arguments of a Union type if `response_type` is a union, otherwise return an empty tuple.""" |
24 | 17 | # similar to `pydantic_ai_slim/pydantic_ai/_result.py:get_union_args` |
@@ -100,3 +93,15 @@ async def run_in_executor(func: Callable[_P, _R], *args: _P.args, **kwargs: _P.k |
100 | 93 | return await asyncio.get_running_loop().run_in_executor(None, partial(func, *args, **kwargs)) |
101 | 94 | else: |
102 | 95 | return await asyncio.get_running_loop().run_in_executor(None, func, *args) # type: ignore |
| 96 | + |
| 97 | + |
| 98 | +def run_until_complete(coro: Coroutine[None, None, _R]) -> _R: |
| 99 | + if sys.version_info < (3, 11): |
| 100 | + try: |
| 101 | + loop = asyncio.new_event_loop() |
| 102 | + return loop.run_until_complete(coro) |
| 103 | + finally: |
| 104 | + loop.close() |
| 105 | + else: |
| 106 | + with asyncio.runners.Runner(loop_factory=asyncio.new_event_loop) as runner: |
| 107 | + return runner.run(coro) |
0 commit comments