Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions injection/_core/common/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
from threading import RLock
from typing import Any, ContextManager, Final

_PYTHON_INJECTION_THREADSAFE: Final[bool] = bool(getenv("PYTHON_INJECTION_THREADSAFE"))
_PYTHON_INJECTION_THREADSAFE: Final[bool] = bool(
int(getenv("PYTHON_INJECTION_THREADSAFE", 0))
)


def get_lock(threadsafe: bool | None = None) -> ContextManager[Any]:
cond = _PYTHON_INJECTION_THREADSAFE if threadsafe is None else threadsafe
return RLock() if cond else nullcontext()
threadsafe = _PYTHON_INJECTION_THREADSAFE if threadsafe is None else threadsafe
return RLock() if threadsafe else nullcontext()
31 changes: 26 additions & 5 deletions injection/_core/injectables.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable, MutableMapping
from contextlib import suppress
from collections.abc import Awaitable, Callable, Iterator, MutableMapping
from contextlib import contextmanager, suppress
from dataclasses import dataclass, field
from functools import partial
from typing import (
Expand Down Expand Up @@ -53,11 +53,13 @@ def get_instance(self) -> T:


class CacheLogic[T]:
__slots__ = ("__semaphore",)
__slots__ = ("__is_instantiating", "__semaphore")

__is_instantiating: bool
__semaphore: AsyncContextManager[Any]

def __init__(self) -> None:
self.__is_instantiating = False
self.__semaphore = AsyncSemaphore(1)

async def aget_or_create[K](
Expand All @@ -66,11 +68,14 @@ async def aget_or_create[K](
key: K,
factory: Callable[..., Awaitable[T]],
) -> T:
self.__fail_if_instantiating()
async with self.__semaphore:
with suppress(KeyError):
return cache[key]

instance = await factory()
with self.__instantiating():
instance = await factory()

cache[key] = instance

return instance
Expand All @@ -81,13 +86,29 @@ def get_or_create[K](
key: K,
factory: Callable[..., T],
) -> T:
self.__fail_if_instantiating()
with suppress(KeyError):
return cache[key]

instance = factory()
with self.__instantiating():
instance = factory()

cache[key] = instance
return instance

def __fail_if_instantiating(self) -> None:
if self.__is_instantiating:
raise RecursionError("Recursive call detected during instantiation.")

@contextmanager
def __instantiating(self) -> Iterator[None]:
self.__is_instantiating = True

try:
yield
finally:
self.__is_instantiating = False


@dataclass(repr=False, eq=False, frozen=True, slots=True)
class SingletonInjectable[T](Injectable[T]):
Expand Down
9 changes: 5 additions & 4 deletions injection/_core/locator.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def make_injected_function[**P, T](
self,
wrapped: Callable[P, T],
/,
threadsafe: bool | None = ...,
) -> Callable[P, T]:
raise NotImplementedError

Expand Down Expand Up @@ -108,24 +109,24 @@ def request(self, provider: InjectionProvider) -> Injectable[T]:

injectable = _make_injectable(
self.factory,
provider.make_injected_function(self.recipe), # type: ignore[misc]
provider.make_injected_function(self.recipe, threadsafe=False), # type: ignore[misc]
)
self.injectables[provider] = injectable
return injectable


@dataclass(repr=False, eq=False, frozen=True, slots=True)
class StaticInjectableBroker[T](InjectableBroker[T]):
value: Injectable[T]
injectable: Injectable[T]

def get(self, provider: InjectionProvider) -> Injectable[T] | None:
return self.value
return self.injectable

def is_locked(self, provider: InjectionProvider) -> bool:
return False

def request(self, provider: InjectionProvider) -> Injectable[T]:
return self.value
return self.injectable

@classmethod
def from_factory(
Expand Down
1 change: 0 additions & 1 deletion injection/_core/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ def _bind_scope(
kind: ScopeKind | ScopeKindStr,
threadsafe: bool | None,
) -> Iterator[ScopeFacade]:
kind = ScopeKind(kind)
lock = get_lock(threadsafe)

with lock:
Expand Down
15 changes: 15 additions & 0 deletions tests/test_injectable.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,18 @@ def my_enum_recipe() -> MyEnum:

value = get_instance(MyEnum)
assert isinstance(value, MyEnum)

async def test_injectable_with_circular_dependency_raise_recursion_error(self):
class A: ...

@injectable
@dataclass
class B:
a: A

@injectable
async def a_factory(_b: B) -> A:
return A()

with pytest.raises(RecursionError):
await aget_instance(A)
15 changes: 15 additions & 0 deletions tests/test_singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,18 @@ class C(B): ...

a = get_instance(A)
assert isinstance(a, C)

async def test_singleton_with_circular_dependency_raise_recursion_error(self):
class A: ...

@singleton
@dataclass
class B:
a: A

@singleton
async def a_factory(_b: B) -> A:
return A()

with pytest.raises(RecursionError):
await aget_instance(A)
Loading