python-dependency-injector/objects/providers.py

313 lines
8.3 KiB
Python
Raw Normal View History

2015-03-09 01:01:39 +03:00
"""Standard providers."""
2015-01-04 17:26:33 +03:00
from collections import Iterable
2015-02-23 11:47:38 +03:00
from .injections import (
Injection,
InitArg,
Attribute,
Method,
)
2015-01-10 12:24:25 +03:00
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
2015-01-11 16:03:45 +03:00
__is_objects_provider__ = True
2015-01-11 19:10:11 +03:00
__overridden_by__ = list()
def __init__(self):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-11 19:10:11 +03:00
self.__overridden_by__ = 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-01-11 19:10:11 +03:00
def __override__(self, provider):
2015-03-09 01:01:39 +03:00
"""Override provider with another provider."""
2015-01-11 19:10:11 +03:00
self.__overridden_by__.append(provider)
2015-02-23 01:16:27 +03:00
def delegate(self):
2015-03-09 01:01:39 +03:00
"""Return provider delegate."""
2015-02-25 02:48:51 +03:00
return ProviderDelegate(self)
class ProviderDelegate(Provider):
2015-03-09 01:01:39 +03:00
"""Provider's delegate."""
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 = delegated
super(ProviderDelegate, self).__init__()
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-01-10 12:24:25 +03:00
def __init__(self, provides, *injections):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-04 17:26:33 +03:00
self.provides = provides
2015-03-09 01:01:39 +03:00
self.init_injections = _fetch_injections(injections, InitArg)
self.attribute_injections = _fetch_injections(injections, Attribute)
self.method_injections = _fetch_injections(injections, Method)
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."""
2015-01-11 19:10:11 +03:00
if self.__overridden_by__:
return self.__overridden_by__[-1].__call__(*args, **kwargs)
2015-03-09 01:01:39 +03:00
init_injections = dict(((injection.name, injection.value)
for injection in self.init_injections))
2015-01-10 12:24:25 +03:00
init_injections.update(kwargs)
2015-01-04 17:26:33 +03:00
2015-03-09 01:01:39 +03:00
instance = self.provides(*args, **init_injections)
2015-01-10 12:24:25 +03:00
2015-03-09 01:01:39 +03:00
if not self.attribute_injections:
for injection in self.attribute_injections:
setattr(instance, injection.name, injection.value)
2015-01-10 12:24:25 +03:00
2015-03-09 01:01:39 +03:00
if not self.method_injections:
for injection in self.method_injections:
getattr(instance, injection.name)(injection.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.
"""
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-01-28 01:21:31 +03:00
def _reset_instance(self):
2015-03-09 01:01:39 +03:00
"""Reset instance."""
2015-01-28 01:21:31 +03:00
self.instance = None
class Scoped(Singleton):
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
"""
def __init__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-28 01:21:31 +03:00
self.is_in_scope = None
super(Scoped, self).__init__(*args, **kwargs)
def in_scope(self):
2015-03-09 01:01:39 +03:00
"""Set provider in "in scope" state."""
2015-01-28 01:21:31 +03:00
self.is_in_scope = True
self._reset_instance()
def out_of_scope(self):
2015-03-09 01:01:39 +03:00
"""Set provider in "out of scope" state."""
2015-01-28 01:21:31 +03:00
self.is_in_scope = False
self._reset_instance()
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-01-28 01:21:31 +03:00
if not self.is_in_scope:
2015-03-09 01:01:39 +03:00
raise RuntimeError('Trying to provide {} '.format(self.provides) +
'while provider is not in scope')
2015-01-28 01:21:31 +03:00
return super(Scoped, self).__call__(*args, **kwargs)
def __enter__(self):
2015-03-09 01:01:39 +03:00
"""Make provider to be in scope."""
2015-01-28 01:21:31 +03:00
self.in_scope()
return self
def __exit__(self, *_):
2015-03-09 01:01:39 +03:00
"""Make provider to be out of scope."""
2015-01-28 01:21:31 +03:00
self.out_of_scope()
2015-01-04 17:26:33 +03:00
class ExternalDependency(Provider):
2015-03-09 01:01:39 +03:00
"""External dependency provider."""
2015-03-09 01:01:39 +03:00
def __init__(self, instance_of):
"""Initializer."""
if not isinstance(instance_of, Iterable):
instance_of = (instance_of,)
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 = provider
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
if not self.dependency:
raise ValueError('Dependency is not satisfied')
result = self.dependency.__call__(*args, **kwargs)
2015-03-09 01:01:39 +03:00
is_instance = any((isinstance(result, possible_type)
for possible_type in self.instance_of))
if not is_instance:
raise TypeError('{} is not an '.format(result) +
'instance of {}'.format(self.instance_of))
return result
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.
"""
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."""
2015-01-11 19:10:11 +03:00
if self.__overridden_by__:
return self.__overridden_by__[-1].__call__()
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.
2015-01-28 14:08:54 +03:00
Callable provider will provide callable calls with some predefined
2015-01-28 01:48:33 +03:00
dependencies injections.
"""
def __init__(self, calls, *injections):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-28 01:48:33 +03:00
self.calls = calls
2015-03-09 01:01:39 +03:00
self.injections = _fetch_injections(injections, 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."""
2015-01-28 01:48:33 +03:00
if self.__overridden_by__:
return self.__overridden_by__[-1].__call__(*args, **kwargs)
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.calls(*args, **injections)
2015-01-28 14:08:54 +03:00
class _DeferredConfig(Provider):
2015-03-09 01:01:39 +03:00
"""Deferred config provider.
2015-01-28 14:08:54 +03:00
Deferred config providers provide an value from the root config object.
"""
2015-01-28 15:25:27 +03:00
2015-01-28 14:08:54 +03:00
def __init__(self, paths, root_config):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-28 14:08:54 +03:00
self.paths = paths
self.root_config = root_config
super(_DeferredConfig, self).__init__()
def __getattr__(self, item):
2015-03-09 01:01:39 +03:00
"""Return instance of deferred config."""
2015-01-28 14:08:54 +03:00
return _DeferredConfig(paths=self.paths + (item,),
root_config=self.root_config)
def __call__(self, *args, **kwargs):
2015-03-09 01:01:39 +03:00
"""Return provided instance."""
2015-01-28 14:08:54 +03:00
return self.root_config(self.paths)
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
deferred config objects for all undefined attribute calls.
"""
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."""
2015-01-28 14:08:54 +03:00
return _DeferredConfig(paths=(item,),
root_config=self)
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:
value = value[path]
return value
2015-03-09 01:01:39 +03:00
def _fetch_injections(injections, injection_type):
"""Fetch injections of injection type from list."""
return tuple([injection
for injection in injections
if isinstance(injection, injection_type)])