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
6 changes: 3 additions & 3 deletions injection/_core/common/asynchronous.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
from dataclasses import dataclass
from typing import Any, NoReturn, Protocol, runtime_checkable

AsyncSemaphore: Callable[[int], AbstractAsyncContextManager[Any]]
AsyncLock: Callable[[], AbstractAsyncContextManager[Any]]

try:
import anyio

except ImportError: # pragma: no cover
import asyncio

AsyncSemaphore = asyncio.Semaphore
AsyncLock = asyncio.Lock

else:
AsyncSemaphore = anyio.Semaphore
AsyncLock = anyio.Lock


@dataclass(repr=False, eq=False, frozen=True, slots=True)
Expand Down
10 changes: 5 additions & 5 deletions injection/_core/injectables.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
runtime_checkable,
)

from injection._core.common.asynchronous import AsyncSemaphore, Caller
from injection._core.common.asynchronous import AsyncLock, Caller
from injection._core.common.type import InputType
from injection._core.scope import Scope, get_first_scope, in_scope_cache
from injection._core.slots import SlotKey
Expand Down Expand Up @@ -51,20 +51,20 @@ def get_instance(self) -> T:


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

__semaphore: AbstractAsyncContextManager[Any]
__lock: AbstractAsyncContextManager[Any]

def __init__(self) -> None:
self.__semaphore = AsyncSemaphore(1)
self.__lock = AsyncLock()

async def aget_or_create[K](
self,
cache: MutableMapping[K, T],
key: K,
factory: Callable[..., Awaitable[T]],
) -> T:
async with self.__semaphore:
async with self.__lock:
with suppress(KeyError):
return cache[key]

Expand Down
Loading