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
28 changes: 22 additions & 6 deletions injection/_core/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,21 @@ def _bind_scope(
stack.close()


class _SealedScopeCache(MutableMapping[Any, Any]):
__slots__ = ()

@staticmethod
def guard(*args: Any, **kwargs: Any) -> NoReturn:
raise ScopeError("Can't access cache of an exited scope.")

__delitem__ = __getitem__ = __iter__ = __len__ = __setitem__ = guard


_sealed_cache = _SealedScopeCache()

del _SealedScopeCache


@runtime_checkable
class Scope(Protocol):
__slots__ = ()
Expand All @@ -227,14 +242,13 @@ def enter[T](self, context_manager: ContextManager[T]) -> T:
raise NotImplementedError


@dataclass(repr=False, frozen=True, slots=True)
@dataclass(repr=False, eq=False, slots=True)
class BaseScope[T](Scope, ABC):
delegate: T
cache: MutableMapping[SlotKey[Any], Any] = field(
default_factory=dict,
init=False,
hash=False,
)
cache: MutableMapping[SlotKey[Any], Any] = field(default_factory=dict, init=False)

def close(self) -> None:
self.cache = _sealed_cache


class AsyncScope(BaseScope[AsyncExitStack]):
Expand All @@ -253,6 +267,7 @@ async def __aexit__(
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> Any:
self.close()
return await self.delegate.__aexit__(exc_type, exc_value, traceback)

async def aenter[T](self, context_manager: AsyncContextManager[T]) -> T:
Expand All @@ -278,6 +293,7 @@ def __exit__(
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> Any:
self.close()
return self.delegate.__exit__(exc_type, exc_value, traceback)

async def aenter[T](self, context_manager: AsyncContextManager[T]) -> NoReturn:
Expand Down
10 changes: 9 additions & 1 deletion tests/core/test_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import pytest

from injection import define_scope, find_instance, scoped
from injection import SlotKey, define_scope, find_instance, scoped
from injection.exceptions import ScopeAlreadyDefinedError, ScopeError


Expand Down Expand Up @@ -35,3 +35,11 @@ def assertion() -> None:
with ThreadPoolExecutor() as executor:
with define_scope("test"):
executor.submit(assertion)


def test_define_scope_with_sealed_raise_scope_error():
with define_scope("test") as scope:
...

with pytest.raises(ScopeError):
scope.set_slot(SlotKey(), object())
12 changes: 6 additions & 6 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.