diff --git a/injector/__init__.py b/injector/__init__.py index e53b762..0d49dd7 100644 --- a/injector/__init__.py +++ b/injector/__init__.py @@ -1263,9 +1263,8 @@ def _recreate_annotated_origin(annotated_type: Any) -> Any: 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 diff --git a/injector_test.py b/injector_test.py index ade7ba9..f4b50bf 100644 --- a/injector_test.py +++ b/injector_test.py @@ -1761,6 +1761,14 @@ def function(a: Inject[Inject[int]]) -> None: assert get_bindings(function) == {'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(): @@ -1768,7 +1776,7 @@ def test_get_bindings_for_pep_604(): 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: