Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Try to inject parameter value if default value is None #110

Merged
merged 6 commits into from
Apr 22, 2024
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
5 changes: 4 additions & 1 deletion src/in_n_out/_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,7 +778,10 @@ def _exec(*args: P.args, **kwargs: P.kwargs) -> R:
# first, get and call the provider functions for each parameter type:
_injected_names: set[str] = set()
for param in sig.parameters.values():
if param.name not in bound.arguments:
if (
param.name not in bound.arguments
or bound.arguments[param.name] is None
):
provided = self.provide(param.annotation)
if provided is not None or is_optional(param.annotation):
logger.debug(
Expand Down
15 changes: 15 additions & 0 deletions tests/test_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,3 +296,18 @@ def f(i: Optional[Thing]) -> Optional[Thing]:
thing = Thing()
with register(providers={Optional[Thing]: lambda: thing}):
assert inject(f)() is thing


def test_inject_into_optional_with_default() -> None:
class Thing: ...

def f(i: Optional[Thing] = None) -> Optional[Thing]:
return i

thing = Thing()
with register(providers={Optional[Thing]: lambda: thing}):
assert inject(f)() is thing
with register(providers={Thing: lambda: thing}):
assert inject(f)() is thing

assert inject(f)() is None
Loading