diff --git a/di/container.py b/di/container.py index 3fadf1a7..852b5f37 100644 --- a/di/container.py +++ b/di/container.py @@ -46,7 +46,10 @@ class Container: _executor: Union[AsyncExecutor, SyncExecutor] def __init__( - self, executor: Optional[Union[AsyncExecutor, SyncExecutor]] = None + self, + *, + default_scope: Scope = None, + executor: Optional[Union[AsyncExecutor, SyncExecutor]] = None, ) -> None: self._context = ContextVar("context") state = ContainerState() @@ -54,6 +57,7 @@ def __init__( state.cached_values.set(Container, self, scope="container") self._context.set(state) self._executor = executor or DefaultExecutor() + self._default_scope = default_scope @property def _state(self) -> ContainerState: @@ -248,7 +252,7 @@ def execute_sync( and then disable scope validation in subsequent runs with `validate_scope=False`. """ results: Dict[Task[Any], Any] = {} - with self.enter_local_scope(None): + with self.enter_local_scope(self._default_scope): if validate_scopes: self._validate_scopes(solved) @@ -277,7 +281,7 @@ async def execute_async( and then disable scope validation in subsequent runs with `validate_scope=False`. """ results: Dict[Task[Any], Any] = {} - async with self.enter_local_scope(None): + async with self.enter_local_scope(self._default_scope): if validate_scopes: self._validate_scopes(solved) diff --git a/pyproject.toml b/pyproject.toml index 4d658f7f..db0b4bbf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "di" -version = "0.7.4" +version = "0.8.0" description = "Autowiring dependency injection" authors = ["Adrian Garcia Badaracco "] readme = "README.md" diff --git a/tests/test_container.py b/tests/test_container.py new file mode 100644 index 00000000..e59bd805 --- /dev/null +++ b/tests/test_container.py @@ -0,0 +1,13 @@ +from typing import Generator + +from di import Container, Dependant + + +def test_default_scope() -> None: + def dep() -> Generator[int, None, None]: + yield 1 + + container = Container(default_scope=1234) + + res = container.execute_sync(container.solve(Dependant(dep, scope=1234))) + assert res == 1