From 56598d7ad3644a835f0c2e03eb4ffa4776ddd333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Mandart?= Date: Wed, 21 Oct 2026 14:39:12 +0200 Subject: [PATCH] refactor: Replace the async semaphore with a lock A semaphore with a single slot behaves like a lock; using a lock states the intent directly. Co-Authored-By: Claude Opus 5.5 (1M context) --- injection/_core/common/asynchronous.py | 6 +++--- injection/_core/injectables.py | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/injection/_core/common/asynchronous.py b/injection/_core/common/asynchronous.py index bbb647f..91b2d27 100644 --- a/injection/_core/common/asynchronous.py +++ b/injection/_core/common/asynchronous.py @@ -4,7 +4,7 @@ from dataclasses import dataclass from typing import Any, NoReturn, Protocol, runtime_checkable -AsyncSemaphore: Callable[[int], AbstractAsyncContextManager[Any]] +AsyncLock: Callable[[], AbstractAsyncContextManager[Any]] try: import anyio @@ -12,10 +12,10 @@ 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) diff --git a/injection/_core/injectables.py b/injection/_core/injectables.py index 14b464d..ba6c4b8 100644 --- a/injection/_core/injectables.py +++ b/injection/_core/injectables.py @@ -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 @@ -51,12 +51,12 @@ 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, @@ -64,7 +64,7 @@ async def aget_or_create[K]( key: K, factory: Callable[..., Awaitable[T]], ) -> T: - async with self.__semaphore: + async with self.__lock: with suppress(KeyError): return cache[key]