Skip to content

Commit

Permalink
Don't crash on a parameters declared to have type Optional[T]
Browse files Browse the repository at this point in the history
We may change the behaviour of this in the future but I think it's
important to not crash now.
  • Loading branch information
Jakub Stasiak committed Oct 20, 2016
1 parent 4d8108b commit 6a8d73a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Technically backwards incompatible:
Python 3-style annotations are used. See
https://www.python.org/dev/peps/pep-0484/#forward-references for details.

Optional parameters are treated as compulsory for the purpose of injection.

0.11.1
------

Expand Down
10 changes: 9 additions & 1 deletion injector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import warnings
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from typing import Any, Generic, get_type_hints, TypeVar
from typing import Any, Generic, get_type_hints, TypeVar, Union


try:
Expand Down Expand Up @@ -921,6 +921,14 @@ def _infer_injected_bindings(callable):
bindings.pop(spec.varargs, None)
bindings.pop(spec.varkw, None)

for k, v in list(bindings.items()):
if v is not Any and issubclass(v, Union):
# We don't treat Optional parameters in any special way at the moment
union_members = v.__union_params__
new_members = tuple(set(union_members) - {type(None)})
new_union = Union[new_members]
bindings[k] = new_union

return bindings


Expand Down
8 changes: 8 additions & 0 deletions injector_test_py3.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,11 @@ def fun(a: Any) -> None:
# it quickly gets helpful when the stack gets deeper.
with pytest.raises(CallError):
injector.call_with_injection(fun)


def test_optionals_are_ignored_for_now():
@inject
def fun(s: str = None):
return s

assert Injector().call_with_injection(fun) == ''

0 comments on commit 6a8d73a

Please sign in to comment.