Skip to content

Commit fa147a8

Browse files
authored
feat: ✨ Add support for executing async recipes in sync environment
1 parent 6f2ff06 commit fa147a8

File tree

3 files changed

+36
-29
lines changed

3 files changed

+36
-29
lines changed

injection/_core/common/asynchronous.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
import asyncio
12
from abc import abstractmethod
23
from collections.abc import Awaitable, Callable, Generator
34
from dataclasses import dataclass
4-
from typing import Any, NoReturn, Protocol, runtime_checkable
5+
from typing import Any, Protocol, runtime_checkable
56

67

78
@dataclass(repr=False, eq=False, frozen=True, slots=True)
@@ -32,10 +33,16 @@ class AsyncCaller[**P, T](Caller[P, T]):
3233
async def acall(self, /, *args: P.args, **kwargs: P.kwargs) -> T:
3334
return await self.callable(*args, **kwargs)
3435

35-
def call(self, /, *args: P.args, **kwargs: P.kwargs) -> NoReturn:
36-
raise RuntimeError(
37-
"Synchronous call isn't supported for an asynchronous Callable."
38-
)
36+
def call(self, /, *args: P.args, **kwargs: P.kwargs) -> T:
37+
loop = asyncio.get_event_loop()
38+
39+
if loop.is_running():
40+
raise RuntimeError(
41+
"Can't call an asynchronous function in a synchronous context."
42+
)
43+
44+
coroutine = self.callable(*args, **kwargs)
45+
return loop.run_until_complete(coroutine)
3946

4047

4148
@dataclass(repr=False, eq=False, frozen=True, slots=True)

injection/_core/module.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,8 @@ def __str__(self) -> str:
7878
length = len(self.classes)
7979
formatted_types = ", ".join(f"`{cls}`" for cls in self.classes)
8080
return (
81-
f"{length} dependenc{"ies" if length > 1 else "y"} have been "
82-
f"updated{f": {formatted_types}" if formatted_types else ""}."
81+
f"{length} dependenc{'ies' if length > 1 else 'y'} have been "
82+
f"updated{f': {formatted_types}' if formatted_types else ''}."
8383
)
8484

8585

poetry.lock

Lines changed: 22 additions & 22 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)