Skip to content

Commit 05c204d

Browse files
authored
fix: 🐛 ScopeFacade can be threadsafe
1 parent 66da89a commit 05c204d

2 files changed

Lines changed: 30 additions & 28 deletions

File tree

injection/_core/scope.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,10 @@ def _bind_scope(
223223
)
224224

225225
stack = ExitStack()
226-
binder = states[name].bind(scope)
227-
stack.enter_context(binder)
226+
stack.enter_context(states[name].bind(scope))
228227

229228
try:
230-
yield _UserScope(scope)
229+
yield _UserScope(scope, lock)
231230

232231
finally:
233232
with lock:
@@ -325,16 +324,19 @@ def slot_map(self, mapping: Mapping[SlotKey[Any], Any], /) -> Self:
325324
@dataclass(repr=False, frozen=True, slots=True)
326325
class _UserScope(ScopeFacade):
327326
scope: Scope
327+
lock: ContextManager[Any]
328328

329329
def set_slot[T](self, key: SlotKey[T], value: T) -> Self:
330330
return self.slot_map({key: value})
331331

332332
def slot_map(self, mapping: Mapping[SlotKey[Any], Any], /) -> Self:
333333
cache = self.scope.cache
334334

335-
for slot_key in mapping:
336-
if slot_key in cache:
337-
raise InjectionError("Slot already set.")
335+
with self.lock:
336+
for slot_key in mapping:
337+
if slot_key in cache:
338+
raise InjectionError("Slot already set.")
339+
340+
cache.update(mapping)
338341

339-
cache.update(mapping)
340342
return self

uv.lock

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

0 commit comments

Comments
 (0)