making pep257 and flake8 happy

This commit is contained in:
Roman Mogilatov 2015-03-09 00:01:39 +02:00
parent 36b1413868
commit e1f2d5e3b8
4 changed files with 124 additions and 216 deletions

View File

@ -1,6 +1,4 @@
""" """Objects."""
`Objects` library.
"""
from .catalog import AbstractCatalog, overrides from .catalog import AbstractCatalog, overrides
from .providers import (Provider, NewInstance, Singleton, Class, Object, from .providers import (Provider, NewInstance, Singleton, Class, Object,
@ -8,11 +6,11 @@ from .providers import (Provider, NewInstance, Singleton, Class, Object,
from .injections import InitArg, Attribute, Method from .injections import InitArg, Attribute, Method
__all__ = ['AbstractCatalog', 'overrides', __all__ = ('AbstractCatalog', 'overrides',
# Providers # Providers
'Provider', 'NewInstance', 'Singleton', 'Class', 'Provider', 'NewInstance', 'Singleton', 'Class',
'Object', 'Function', 'Value', 'Object', 'Function', 'Value',
# Injections # Injections
'InitArg', 'Attribute', 'Method'] 'InitArg', 'Attribute', 'Method')

View File

@ -1,28 +1,18 @@
""" """Catalog module."""
Catalog module.
"""
from .providers import Provider from .providers import Provider
class AbstractCatalog(object): class AbstractCatalog(object):
"""
Abstract object provides catalog. """Abstract object provides catalog."""
"""
def __init__(self, *used_providers): def __init__(self, *used_providers):
""" """Initializer."""
Initializer.
"""
self.__used_providers__ = set(used_providers) self.__used_providers__ = set(used_providers)
def __getattribute__(self, item): def __getattribute__(self, item):
""" """Return providers."""
Returns providers.
:param item:
:return:
"""
attribute = super(AbstractCatalog, self).__getattribute__(item) attribute = super(AbstractCatalog, self).__getattribute__(item)
if item in ('__used_providers__',): if item in ('__used_providers__',):
return attribute return attribute
@ -34,9 +24,7 @@ class AbstractCatalog(object):
@classmethod @classmethod
def __all_providers__(cls, provider_type=Provider): def __all_providers__(cls, provider_type=Provider):
""" """Return set of all class providers."""
Returns set of all class providers.
"""
providers = set() providers = set()
for attr_name in set(dir(cls)) - set(dir(AbstractCatalog)): for attr_name in set(dir(cls)) - set(dir(AbstractCatalog)):
provider = getattr(cls, attr_name) provider = getattr(cls, attr_name)
@ -48,23 +36,18 @@ class AbstractCatalog(object):
@classmethod @classmethod
def __override___(cls, overriding): def __override___(cls, overriding):
""" """
Overrides current catalog providers by overriding catalog providers. Override current catalog providers by overriding catalog providers.
:param overriding: AbstractCatalog :param overriding: AbstractCatalog
""" """
overriden = overriding.__all_providers__() - cls.__all_providers__() overridden = overriding.__all_providers__() - cls.__all_providers__()
for name, provider in overriden: for name, provider in overridden:
overridden_provider = getattr(cls, name) overridden_provider = getattr(cls, name)
overridden_provider.__override__(provider) overridden_provider.__override__(provider)
def overrides(catalog): def overrides(catalog):
""" """Catalog overriding decorator."""
Catalog overriding decorator.
:param catalog:
:return:
"""
def decorator(overriding_catalog): def decorator(overriding_catalog):
catalog.__override___(overriding_catalog) catalog.__override___(overriding_catalog)
return overriding_catalog return overriding_catalog

View File

@ -1,43 +1,33 @@
""" """Injections module."""
Injections module.
"""
class Injection(object): class Injection(object):
"""
Base injection class. """Base injection class."""
"""
def __init__(self, name, injectable): def __init__(self, name, injectable):
""" """Initializer."""
Initializer.
"""
self.name = name self.name = name
self.injectable = injectable self.injectable = injectable
@property @property
def value(self): def value(self):
""" """Return injectable value."""
Returns injectable value.
"""
if hasattr(self.injectable, '__is_objects_provider__'): if hasattr(self.injectable, '__is_objects_provider__'):
return self.injectable() return self.injectable()
return self.injectable return self.injectable
class InitArg(Injection): class InitArg(Injection):
"""
Init argument injection. """Init argument injection."""
"""
class Attribute(Injection): class Attribute(Injection):
"""
Attribute injection. """Attribute injection."""
"""
class Method(Injection): class Method(Injection):
"""
Method injection. """Method injection."""
"""

View File

@ -1,6 +1,4 @@
""" """Standard providers."""
Standard providers.
"""
from collections import Iterable from collections import Iterable
from .injections import ( from .injections import (
@ -12,46 +10,35 @@ from .injections import (
class Provider(object): class Provider(object):
"""
Base provider class. """Base provider class."""
"""
__is_objects_provider__ = True __is_objects_provider__ = True
__overridden_by__ = list() __overridden_by__ = list()
def __init__(self): def __init__(self):
""" """Initializer."""
Initializer.
"""
self.__overridden_by__ = list() self.__overridden_by__ = list()
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
raise NotImplementedError() raise NotImplementedError()
def __override__(self, provider): def __override__(self, provider):
""" """Override provider with another provider."""
Overrides provider with another provider.
"""
self.__overridden_by__.append(provider) self.__overridden_by__.append(provider)
def delegate(self): def delegate(self):
""" """Return provider delegate."""
Returns provider delegate.
"""
return ProviderDelegate(self) return ProviderDelegate(self)
class ProviderDelegate(Provider): class ProviderDelegate(Provider):
"""
Provider's delegate. """Provider's delegate."""
"""
def __init__(self, delegated): def __init__(self, delegated):
""" """Initializer.
Initializer.
:type delegated: Provider :type delegated: Provider
""" """
@ -59,153 +46,116 @@ class ProviderDelegate(Provider):
super(ProviderDelegate, self).__init__() super(ProviderDelegate, self).__init__()
def __call__(self): def __call__(self):
""" """Return provided instance."""
Returns provided instance.
"""
return self.delegated.__call__ return self.delegated.__call__
def prepare_injections(injections):
"""
Prepares injections list to injection.
"""
return [(injection.name, injection.value) for injection in injections]
def fetch_injections(injections, injection_type):
"""
Fetches injections of injection type from list.
"""
return tuple([injection
for injection in injections
if isinstance(injection, injection_type)])
class NewInstance(Provider): class NewInstance(Provider):
"""
"""New instance provider.
New instance providers will create and return new instance on every call. New instance providers will create and return new instance on every call.
""" """
def __init__(self, provides, *injections): def __init__(self, provides, *injections):
""" """Initializer."""
Initializer.
"""
self.provides = provides self.provides = provides
self.init_injections = fetch_injections(injections, InitArg) self.init_injections = _fetch_injections(injections, InitArg)
self.attribute_injections = fetch_injections(injections, Attribute) self.attribute_injections = _fetch_injections(injections, Attribute)
self.method_injections = fetch_injections(injections, Method) self.method_injections = _fetch_injections(injections, Method)
super(NewInstance, self).__init__() super(NewInstance, self).__init__()
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
if self.__overridden_by__: if self.__overridden_by__:
return self.__overridden_by__[-1].__call__(*args, **kwargs) return self.__overridden_by__[-1].__call__(*args, **kwargs)
init_injections = prepare_injections(self.init_injections) init_injections = dict(((injection.name, injection.value)
init_injections = dict(init_injections) for injection in self.init_injections))
init_injections.update(kwargs) init_injections.update(kwargs)
provided = self.provides(*args, **init_injections) instance = self.provides(*args, **init_injections)
attribute_injections = prepare_injections(self.attribute_injections) if not self.attribute_injections:
for name, injectable in attribute_injections: for injection in self.attribute_injections:
setattr(provided, name, injectable) setattr(instance, injection.name, injection.value)
method_injections = prepare_injections(self.method_injections) if not self.method_injections:
for name, injectable in method_injections: for injection in self.method_injections:
getattr(provided, name)(injectable) getattr(instance, injection.name)(injection.value)
return provided return instance
class Singleton(NewInstance): class Singleton(NewInstance):
"""
"""Singleton provider.
Singleton provider will create instance once and return it on every call. Singleton provider will create instance once and return it on every call.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
""" """Initializer."""
Initializer.
"""
self.instance = None self.instance = None
super(Singleton, self).__init__(*args, **kwargs) super(Singleton, self).__init__(*args, **kwargs)
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
if not self.instance: if not self.instance:
self.instance = super(Singleton, self).__call__(*args, **kwargs) self.instance = super(Singleton, self).__call__(*args, **kwargs)
return self.instance return self.instance
def _reset_instance(self): def _reset_instance(self):
""" """Reset instance."""
Resets instance.
"""
self.instance = None self.instance = None
class Scoped(Singleton): class Scoped(Singleton):
"""
Scoped provider will create instance once for every scope and return it on every call. """Scoped provider.
Scoped provider will create instance once for every scope and return it
on every call.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
""" """Initializer."""
Initializer.
"""
self.is_in_scope = None self.is_in_scope = None
super(Scoped, self).__init__(*args, **kwargs) super(Scoped, self).__init__(*args, **kwargs)
def in_scope(self): def in_scope(self):
""" """Set provider in "in scope" state."""
Sets provider in "in scope" state.
"""
self.is_in_scope = True self.is_in_scope = True
self._reset_instance() self._reset_instance()
def out_of_scope(self): def out_of_scope(self):
""" """Set provider in "out of scope" state."""
Sets provider in "out of scope" state.
"""
self.is_in_scope = False self.is_in_scope = False
self._reset_instance() self._reset_instance()
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
if not self.is_in_scope: if not self.is_in_scope:
raise RuntimeError('Trying to provide {} while provider is not in scope'.format(self.provides)) raise RuntimeError('Trying to provide {} '.format(self.provides) +
'while provider is not in scope')
return super(Scoped, self).__call__(*args, **kwargs) return super(Scoped, self).__call__(*args, **kwargs)
def __enter__(self): def __enter__(self):
""" """Make provider to be in scope."""
With __enter__() implementation. Makes provider to be in scope.
"""
self.in_scope() self.in_scope()
return self return self
def __exit__(self, *_): def __exit__(self, *_):
""" """Make provider to be out of scope."""
With __exit__() implementation. Makes provider to be out of scope.
"""
self.out_of_scope() self.out_of_scope()
class ExternalDependency(Provider): class ExternalDependency(Provider):
"""
External dependency provider. """External dependency provider."""
"""
def __init__(self, instance_of): def __init__(self, instance_of):
""" """Initializer."""
Initializer
:param instance_of: type
"""
if not isinstance(instance_of, Iterable): if not isinstance(instance_of, Iterable):
instance_of = (instance_of,) instance_of = (instance_of,)
self.instance_of = instance_of self.instance_of = instance_of
@ -213,163 +163,150 @@ class ExternalDependency(Provider):
super(ExternalDependency, self).__init__() super(ExternalDependency, self).__init__()
def satisfy(self, provider): def satisfy(self, provider):
""" """Satisfy an external dependency."""
Satisfies an external dependency.
:param provider: Provider
"""
self.dependency = provider self.dependency = provider
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
if not self.dependency: if not self.dependency:
raise ValueError('Dependency is not satisfied') raise ValueError('Dependency is not satisfied')
result = self.dependency.__call__(*args, **kwargs) result = self.dependency.__call__(*args, **kwargs)
if not any((isinstance(result, possible_type) for possible_type in self.instance_of)): is_instance = any((isinstance(result, possible_type)
raise TypeError('{} is not an instance of {}'.format(result, self.instance_of)) 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 return result
class _StaticProvider(Provider): class _StaticProvider(Provider):
"""
"""Static provider.
Static provider is base implementation that provides exactly the same as Static provider is base implementation that provides exactly the same as
it got on input. it got on input.
""" """
def __init__(self, provides): def __init__(self, provides):
""" """Initializer."""
Initializer.
"""
self.provides = provides self.provides = provides
super(_StaticProvider, self).__init__() super(_StaticProvider, self).__init__()
def __call__(self): def __call__(self):
""" """Return provided instance."""
Returns provided instance.
"""
if self.__overridden_by__: if self.__overridden_by__:
return self.__overridden_by__[-1].__call__() return self.__overridden_by__[-1].__call__()
return self.provides return self.provides
class Class(_StaticProvider): class Class(_StaticProvider):
"""
Class provider provides class. """Class provider provides class."""
"""
class Object(_StaticProvider): class Object(_StaticProvider):
"""
Object provider provides object. """Object provider provides object."""
"""
class Function(_StaticProvider): class Function(_StaticProvider):
"""
Function provider provides function. """Function provider provides function."""
"""
class Value(_StaticProvider): class Value(_StaticProvider):
"""
Value provider provides value. """Value provider provides value."""
"""
class Callable(Provider): class Callable(Provider):
"""
"""Callable provider.
Callable provider will provide callable calls with some predefined Callable provider will provide callable calls with some predefined
dependencies injections. dependencies injections.
""" """
def __init__(self, calls, *injections): def __init__(self, calls, *injections):
""" """Initializer."""
Initializer.
"""
self.calls = calls self.calls = calls
self.injections = fetch_injections(injections, Injection) self.injections = _fetch_injections(injections, Injection)
super(Callable, self).__init__() super(Callable, self).__init__()
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
if self.__overridden_by__: if self.__overridden_by__:
return self.__overridden_by__[-1].__call__(*args, **kwargs) return self.__overridden_by__[-1].__call__(*args, **kwargs)
injections = prepare_injections(self.injections) injections = dict(((injection.name, injection.value)
injections = dict(injections) for injection in self.injections))
injections.update(kwargs) injections.update(kwargs)
return self.calls(*args, **injections) return self.calls(*args, **injections)
class _DeferredConfig(Provider): class _DeferredConfig(Provider):
"""
"""Deferred config provider.
Deferred config providers provide an value from the root config object. Deferred config providers provide an value from the root config object.
""" """
def __init__(self, paths, root_config): def __init__(self, paths, root_config):
""" """Initializer."""
Initializer.
"""
self.paths = paths self.paths = paths
self.root_config = root_config self.root_config = root_config
super(_DeferredConfig, self).__init__() super(_DeferredConfig, self).__init__()
def __getattr__(self, item): def __getattr__(self, item):
""" """Return instance of deferred config."""
Returns instance of deferred config.
"""
return _DeferredConfig(paths=self.paths + (item,), return _DeferredConfig(paths=self.paths + (item,),
root_config=self.root_config) root_config=self.root_config)
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
""" """Return provided instance."""
Returns provided instance.
"""
return self.root_config(self.paths) return self.root_config(self.paths)
class Config(Provider): class Config(Provider):
"""
"""Config provider.
Config provider provides dict values. Also config provider creates Config provider provides dict values. Also config provider creates
deferred config objects for all undefined attribute calls. deferred config objects for all undefined attribute calls.
""" """
def __init__(self, value=None): def __init__(self, value=None):
""" """Initializer."""
Initializer.
"""
if not value: if not value:
value = dict() value = dict()
self.value = value self.value = value
super(Config, self).__init__() super(Config, self).__init__()
def update_from(self, value): def update_from(self, value):
""" """Update current value from another one."""
Updates current value from another one.
"""
self.value.update(value) self.value.update(value)
def __getattr__(self, item): def __getattr__(self, item):
""" """Return instance of deferred config."""
Returns instance of deferred config.
"""
return _DeferredConfig(paths=(item,), return _DeferredConfig(paths=(item,),
root_config=self) root_config=self)
def __call__(self, paths=None): def __call__(self, paths=None):
""" """Return provided instance."""
Returns provided instance.
"""
value = self.value value = self.value
if paths: if paths:
for path in paths: for path in paths:
value = value[path] value = value[path]
return value return value
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)])