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
10 changes: 6 additions & 4 deletions modern_di/providers/context_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ContextProvider(AbstractProvider[types.T_co]):
``ArgumentResolutionError``.
"""

__slots__ = ("_context_type",)
__slots__ = ("context_type",)

def __init__(
self,
Expand All @@ -32,10 +32,12 @@ def __init__(
super().__init__(
scope=scope, bound_type=context_type if isinstance(bound_type, types.UnsetType) else bound_type
)
self._context_type = context_type
# Public, like its sibling ``bound_type`` — the type this provider supplies and
# the key its value is set under in ``context``.
self.context_type = context_type

def __repr__(self) -> str:
return f"ContextProvider(context_type={self._context_type!r}, scope={self.scope!r})"
return f"ContextProvider(context_type={self.context_type!r}, scope={self.scope!r})"

def resolve(self, container: "Container") -> types.T_co | None:
value = self.fetch_context_value(container)
Expand All @@ -47,4 +49,4 @@ def fetch_context_value(self, container: "Container") -> types.T_co | object:
container = container.find_container(self.scope)
if container.closed:
raise exceptions.ContainerClosedError(container_scope=container.scope)
return container.context_registry.find_context(self._context_type)
return container.context_registry.find_context(self.context_type)
5 changes: 5 additions & 0 deletions tests/providers/test_context_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ def test_context_provider_repr() -> None:
assert repr(provider) == "ContextProvider(context_type=<class 'str'>, scope=<Scope.REQUEST: 3>)"


def test_context_provider_exposes_context_type() -> None:
provider = providers.ContextProvider(context_type=datetime.datetime, scope=Scope.REQUEST)
assert provider.context_type is datetime.datetime


@pytest.mark.parametrize("value", [0, False, "", [], {}, 0.0])
def test_context_provider_returns_falsy_values(value: object) -> None:
context_type = type(value)
Expand Down