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
31 changes: 5 additions & 26 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, Iterator, MutableMapping
from contextlib import contextmanager, suppress
from collections.abc import Awaitable, Callable, MutableMapping
from contextlib import suppress
from dataclasses import dataclass, field
from functools import partial
from typing import (
Expand Down Expand Up @@ -53,13 +53,11 @@ def get_instance(self) -> T:


class CacheLogic[T]:
__slots__ = ("__is_instantiating", "__semaphore")
__slots__ = ("__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 @@ -68,14 +66,11 @@ 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]

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

instance = await factory()
cache[key] = instance

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

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

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
15 changes: 0 additions & 15 deletions tests/test_singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,18 +183,3 @@ 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() # pragma: no cover

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