Skip to content

Commit

Permalink
feat: add default_scope parameter to Container
Browse files Browse the repository at this point in the history
  • Loading branch information
adriangb committed Oct 7, 2021
1 parent 4310876 commit 0299746
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
10 changes: 7 additions & 3 deletions di/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,18 @@ 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()
state.cached_values.add_scope("container")
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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "di"
version = "0.7.4"
version = "0.8.0"
description = "Autowiring dependency injection"
authors = ["Adrian Garcia Badaracco <[email protected]>"]
readme = "README.md"
Expand Down
13 changes: 13 additions & 0 deletions tests/test_container.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 0299746

Please sign in to comment.