Skip to content

Support optional parameters #276

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 1 addition & 2 deletions injector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1253,9 +1253,8 @@ def _is_injection_annotation(annotation: Any) -> bool:
if only_explicit_bindings and _inject_marker not in metadata or _noinject_marker in metadata:
del bindings[k]
elif _is_specialization(v, Union) or _is_new_union_type(v):
# We don't treat Optional parameters in any special way at the moment.
union_members = v.__args__
new_members = tuple(set(union_members) - {type(None)})
new_members = tuple(set(union_members))
# mypy stared complaining about this line for some reason:
# error: Variable "new_members" is not valid as a type
new_union = Union[new_members] # type: ignore
Expand Down
10 changes: 9 additions & 1 deletion injector_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1674,14 +1674,22 @@ def function11(a: int) -> 'InvalidForwardReference':
assert get_bindings(function11) == {'a': int}


# This should correctly resolve str | None
@inject
def function12(a: str | None):
pass

assert get_bindings(function12) == {'a': str | None}


# Tests https://github.com/alecthomas/injector/issues/202
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10+")
def test_get_bindings_for_pep_604():
@inject
def function1(a: int | None) -> None:
pass

assert get_bindings(function1) == {'a': int}
assert get_bindings(function1) == {'a': Union[int, None]}

@inject
def function1(a: int | str) -> None:
Expand Down