Add simplified syntax of kwarg injections for `Callable` provider

This commit is contained in:
Roman Mogilatov 2015-09-01 15:21:55 +03:00
parent a1cf735391
commit bb33c925de
2 changed files with 9 additions and 10 deletions

View File

@ -255,22 +255,21 @@ class Callable(Provider):
with some predefined dependency injections. with some predefined dependency injections.
""" """
__slots__ = ('_callback', '_injections') __slots__ = ('_callback', '_kwargs')
def __init__(self, callback, *injections): def __init__(self, callback, **kwargs):
"""Initializer.""" """Initializer."""
if not callable(callback): if not callable(callback):
raise Error('Callable expected, got {0}'.format(str(callback))) raise Error('Callable expected, got {0}'.format(str(callback)))
self._callback = callback self._callback = callback
self._injections = tuple((injection self._kwargs = tuple((KwArg(name, value)
for injection in injections for name, value in six.iteritems(kwargs)))
if is_kwarg_injection(injection)))
super(Callable, self).__init__() super(Callable, self).__init__()
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
return self._callback(*args, **get_injectable_kwargs(kwargs, return self._callback(*args, **get_injectable_kwargs(kwargs,
self._injections)) self._kwargs))
class Config(Provider): class Config(Provider):

View File

@ -429,9 +429,9 @@ class CallableTests(unittest.TestCase):
def setUp(self): def setUp(self):
"""Set test cases environment up.""" """Set test cases environment up."""
self.provider = di.Callable(self.example, self.provider = di.Callable(self.example,
di.KwArg('arg1', 'a1'), arg1='a1',
di.KwArg('arg2', 'a2'), arg2='a2',
di.KwArg('arg3', 'a3')) arg3='a3')
def test_init_with_not_callable(self): def test_init_with_not_callable(self):
"""Test creation of provider with not callable.""" """Test creation of provider with not callable."""
@ -448,7 +448,7 @@ class CallableTests(unittest.TestCase):
def test_call_with_args(self): def test_call_with_args(self):
"""Test provider call with kwargs priority.""" """Test provider call with kwargs priority."""
provider = di.Callable(self.example, provider = di.Callable(self.example,
di.KwArg('arg3', 'a3')) arg3='a3')
self.assertEqual(provider(1, 2), (1, 2, 'a3')) self.assertEqual(provider(1, 2), (1, 2, 'a3'))
def test_call_with_kwargs_priority(self): def test_call_with_kwargs_priority(self):