python-dependency-injector/objects/providers.py

345 lines
9.6 KiB
Python
Raw Normal View History

"""Providers module."""
2015-01-04 17:26:33 +03:00
from inspect import isclass
2015-03-10 12:51:13 +03:00
from .utils import ensure_is_provider
from .utils import is_injection
from .utils import is_init_arg_injection
from .utils import is_attribute_injection
from .utils import is_method_injection
2015-01-10 12:24:25 +03:00
2015-03-13 18:31:07 +03:00
from .errors import Error
2015-01-04 17:26:33 +03:00
class Provider(object):
2015-03-09 01:01:39 +03:00
"""Base provider class."""
2015-01-04 17:26:33 +03:00
__IS_OBJECTS_PROVIDER__ = True
2015-03-12 13:49:30 +03:00
__slots__ = ('__IS_OBJECTS_PROVIDER__', 'overridden')
2015-01-11 19:10:11 +03:00
def __init__(self):
2015-03-09 01:01:39 +03:00
"""Initializer."""
self.overridden = list()
2015-01-11 16:03:45 +03:00
2015-01-04 17:26:33 +03:00
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-01-04 17:26:33 +03:00
raise NotImplementedError()
2015-02-23 01:16:27 +03:00
def delegate(self):
"""Return provider's delegate."""
2015-03-14 01:02:01 +03:00
return Delegate(self)
2015-02-25 02:48:51 +03:00
def override(self, provider):
"""Override provider with another provider."""
self.overridden.append(ensure_is_provider(provider))
@property
def last_overriding(self):
"""Return last overriding provider."""
try:
return self.overridden[-1]
except IndexError:
2015-03-13 18:31:07 +03:00
raise Error('Provider {} '.format(str(self)) +
'is not overridden')
2015-02-25 02:48:51 +03:00
2015-03-14 01:02:01 +03:00
class Delegate(Provider):
2015-03-09 01:01:39 +03:00
"""Provider's delegate."""
2015-02-25 02:48:51 +03:00
__slots__ = ('delegated',)
2015-02-25 02:48:51 +03:00
def __init__(self, delegated):
2015-03-09 01:01:39 +03:00
"""Initializer.
2015-02-25 02:48:51 +03:00
:type delegated: Provider
"""
self.delegated = ensure_is_provider(delegated)
2015-03-14 01:02:01 +03:00
super(Delegate, self).__init__()
2015-02-25 02:48:51 +03:00
def __call__(self):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-03-09 01:24:46 +03:00
return self.delegated
2015-02-23 01:16:27 +03:00
2015-01-11 16:03:45 +03:00
2015-03-09 01:01:39 +03:00
class NewInstance(Provider):
2015-01-10 12:24:25 +03:00
2015-03-09 01:01:39 +03:00
"""New instance provider.
2015-01-04 17:26:33 +03:00
New instance providers will create and return new instance on every call.
"""
2015-03-12 13:49:30 +03:00
__slots__ = ('provides', 'init_args', 'attributes', 'methods')
2015-01-10 12:24:25 +03:00
def __init__(self, provides, *injections):
2015-03-09 01:01:39 +03:00
"""Initializer."""
if not isclass(provides):
raise Error('NewInstance provider expects to get class, ' +
'got {} instead'.format(str(provides)))
2015-01-04 17:26:33 +03:00
self.provides = provides
2015-03-11 16:27:38 +03:00
self.init_args = tuple((injection
for injection in injections
if is_init_arg_injection(injection)))
self.attributes = tuple((injection
for injection in injections
if is_attribute_injection(injection)))
self.methods = tuple((injection
for injection in injections
if is_method_injection(injection)))
2015-01-11 19:10:11 +03:00
super(NewInstance, self).__init__()
2015-01-04 17:26:33 +03:00
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if self.overridden:
return self.last_overriding(*args, **kwargs)
2015-01-11 19:10:11 +03:00
init_kwargs = dict(((injection.name, injection.value)
for injection in self.init_args))
init_kwargs.update(kwargs)
2015-01-04 17:26:33 +03:00
instance = self.provides(*args, **init_kwargs)
2015-01-10 12:24:25 +03:00
for attribute in self.attributes:
setattr(instance, attribute.name, attribute.value)
for method in self.methods:
getattr(instance, method.name)(method.value)
2015-01-04 17:26:33 +03:00
2015-03-09 01:01:39 +03:00
return instance
2015-01-04 17:26:33 +03:00
class Singleton(NewInstance):
2015-03-09 01:01:39 +03:00
"""Singleton provider.
2015-01-04 17:26:33 +03:00
Singleton provider will create instance once and return it on every call.
"""
__slots__ = ('instance',)
2015-01-04 17:26:33 +03:00
def __init__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-04 17:26:33 +03:00
self.instance = None
super(Singleton, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-01-04 17:26:33 +03:00
if not self.instance:
self.instance = super(Singleton, self).__call__(*args, **kwargs)
return self.instance
2015-03-15 01:50:24 +03:00
def reset(self):
2015-03-09 01:01:39 +03:00
"""Reset instance."""
2015-01-28 01:21:31 +03:00
self.instance = None
class Scoped(NewInstance):
2015-03-09 01:01:39 +03:00
"""Scoped provider.
Scoped provider will create instance once for every scope and return it
on every call.
2015-01-28 01:21:31 +03:00
"""
__slots__ = ('current_scope', 'scopes_to_instances')
2015-01-28 01:21:31 +03:00
def __init__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Initializer."""
self.current_scope = None
self.scopes_to_instances = dict()
2015-01-28 01:21:31 +03:00
super(Scoped, self).__init__(*args, **kwargs)
def in_scope(self, scope):
2015-03-09 01:01:39 +03:00
"""Set provider in "in scope" state."""
self.current_scope = scope
2015-01-28 01:21:31 +03:00
def out_of_scope(self, scope):
2015-03-09 01:01:39 +03:00
"""Set provider in "out of scope" state."""
self.current_scope = None
try:
del self.scopes_to_instances[scope]
except KeyError:
raise Error('Trying to move out of undefined scope '
'"{}"'.format(scope))
2015-01-28 01:21:31 +03:00
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if not self.current_scope:
2015-03-13 18:31:07 +03:00
raise Error('Trying to provide {} '.format(self.provides) +
'while provider has no active scope')
try:
instance = self.scopes_to_instances[self.current_scope]
except KeyError:
instance = super(Scoped, self).__call__(*args, **kwargs)
self.scopes_to_instances[self.current_scope] = instance
return instance
2015-01-28 01:21:31 +03:00
2015-01-04 17:26:33 +03:00
class ExternalDependency(Provider):
2015-03-09 01:01:39 +03:00
"""External dependency provider."""
2015-03-12 13:49:30 +03:00
__slots__ = ('instance_of', 'dependency')
2015-03-09 01:01:39 +03:00
def __init__(self, instance_of):
"""Initializer."""
self.instance_of = instance_of
self.dependency = None
super(ExternalDependency, self).__init__()
def satisfy(self, provider):
2015-03-09 01:01:39 +03:00
"""Satisfy an external dependency."""
self.dependency = ensure_is_provider(provider)
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if not self.dependency:
2015-03-13 18:31:07 +03:00
raise Error('Dependency is not satisfied')
instance = self.dependency.__call__(*args, **kwargs)
if not isinstance(instance, self.instance_of):
raise Error('{} is not an '.format(instance) +
2015-03-13 18:31:07 +03:00
'instance of {}'.format(self.instance_of))
return instance
2015-01-04 17:26:33 +03:00
class _StaticProvider(Provider):
2015-03-09 01:01:39 +03:00
"""Static provider.
2015-01-04 17:26:33 +03:00
Static provider is base implementation that provides exactly the same as
it got on input.
"""
__slots__ = ('provides',)
2015-01-04 17:26:33 +03:00
def __init__(self, provides):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-04 17:26:33 +03:00
self.provides = provides
2015-01-11 19:10:11 +03:00
super(_StaticProvider, self).__init__()
2015-01-04 17:26:33 +03:00
def __call__(self):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if self.overridden:
return self.last_overriding()
2015-01-04 17:26:33 +03:00
return self.provides
class Class(_StaticProvider):
2015-03-09 01:01:39 +03:00
"""Class provider provides class."""
2015-01-04 17:26:33 +03:00
class Object(_StaticProvider):
2015-03-09 01:01:39 +03:00
"""Object provider provides object."""
2015-01-04 17:26:33 +03:00
class Function(_StaticProvider):
2015-03-09 01:01:39 +03:00
"""Function provider provides function."""
2015-01-04 17:26:33 +03:00
class Value(_StaticProvider):
2015-03-09 01:01:39 +03:00
"""Value provider provides value."""
2015-01-28 01:48:33 +03:00
class Callable(Provider):
2015-03-09 01:01:39 +03:00
"""Callable provider.
Callable provider provides callable that is called on every provider call
with some predefined dependency injections.
2015-01-28 01:48:33 +03:00
"""
__slots__ = ('callback', 'injections')
def __init__(self, callback, *injections):
2015-03-09 01:01:39 +03:00
"""Initializer."""
if not callable(callback):
raise Error('Callable expected, got {}'.format(str(callback)))
self.callback = callback
2015-03-11 16:27:38 +03:00
self.injections = tuple((injection
for injection in injections
if is_injection(injection)))
2015-01-28 01:48:33 +03:00
super(Callable, self).__init__()
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if self.overridden:
return self.last_overriding()
2015-01-28 01:48:33 +03:00
2015-03-09 01:01:39 +03:00
injections = dict(((injection.name, injection.value)
for injection in self.injections))
2015-01-28 01:48:33 +03:00
injections.update(kwargs)
return self.callback(*args, **injections)
2015-01-28 14:08:54 +03:00
class Config(Provider):
2015-03-09 01:01:39 +03:00
"""Config provider.
2015-01-28 14:08:54 +03:00
Config provider provides dict values. Also config provider creates
child config objects for all undefined attribute calls. It makes possible
to create deferred config value provider.
2015-01-28 14:08:54 +03:00
"""
__slots__ = ('value',)
2015-01-28 14:08:54 +03:00
def __init__(self, value=None):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-28 14:08:54 +03:00
if not value:
value = dict()
self.value = value
super(Config, self).__init__()
def update_from(self, value):
2015-03-09 01:01:39 +03:00
"""Update current value from another one."""
2015-01-28 14:08:54 +03:00
self.value.update(value)
def __getattr__(self, item):
2015-03-09 01:01:39 +03:00
"""Return instance of deferred config."""
return _ChildConfig(parents=(item,), root_config=self)
2015-01-28 14:08:54 +03:00
def __call__(self, paths=None):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-01-28 14:08:54 +03:00
value = self.value
if paths:
for path in paths:
try:
value = value[path]
except KeyError:
raise Error('Config key '
'"{}" is undefined'.format('.'.join(paths)))
return value
2015-03-10 12:51:13 +03:00
class _ChildConfig(Provider):
2015-03-10 12:51:13 +03:00
"""Child config provider.
2015-03-10 12:51:13 +03:00
Child config provide an value from the root config object according to
the current path in the config tree.
2015-03-10 12:51:13 +03:00
"""
2015-03-16 12:41:42 +03:00
__slots__ = ('parents', 'root_config')
2015-03-16 12:41:42 +03:00
def __init__(self, parents, root_config):
2015-03-10 12:51:13 +03:00
"""Initializer."""
2015-03-16 12:41:42 +03:00
self.parents = parents
2015-03-10 12:51:13 +03:00
self.root_config = root_config
super(_ChildConfig, self).__init__()
2015-03-10 12:51:13 +03:00
def __getattr__(self, item):
"""Return instance of deferred config."""
return _ChildConfig(parents=self.parents + (item,),
root_config=self.root_config)
2015-03-10 12:51:13 +03:00
def __call__(self, *args, **kwargs):
"""Return provided instance."""
2015-03-16 12:41:42 +03:00
return self.root_config(self.parents)