Make all protected attributes _protected

This commit is contained in:
Roman Mogilatov 2015-07-22 16:42:36 +03:00
parent 541d3c0e4b
commit 040aad93f8
4 changed files with 78 additions and 73 deletions

View File

@ -33,19 +33,19 @@ class AbstractCatalog(object):
providers = dict() providers = dict()
__slots__ = ('__used_providers__',) __slots__ = ('_used_providers',)
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.""" """Return providers."""
attribute = super(AbstractCatalog, self).__getattribute__(item) attribute = super(AbstractCatalog, self).__getattribute__(item)
if item in ('providers', '__used_providers__',): if item in ('providers', '_used_providers',):
return attribute return attribute
if attribute not in self.__used_providers__: if attribute not in self._used_providers:
raise Error('Provider \'{0}\' '.format(item) + raise Error('Provider \'{0}\' '.format(item) +
'is not listed in dependencies') 'is not listed in dependencies')
return attribute return attribute

View File

@ -24,18 +24,18 @@ def inject(injection):
def decorator(callback): def decorator(callback):
"""Dependency injection decorator.""" """Dependency injection decorator."""
if hasattr(callback, '__injections__'): if hasattr(callback, '_injections'):
callback.__injections__ += (injection,) callback._injections += (injection,)
@wraps(callback) @wraps(callback)
def decorated(*args, **kwargs): def decorated(*args, **kwargs):
"""Decorated with dependency injection callback.""" """Decorated with dependency injection callback."""
for injection in getattr(decorated, '__injections__'): for injection in getattr(decorated, '_injections'):
if injection.name not in kwargs: if injection.name not in kwargs:
kwargs[injection.name] = injection.value kwargs[injection.name] = injection.value
return callback(*args, **kwargs) return callback(*args, **kwargs)
setattr(decorated, '__injections__', (injection,)) setattr(decorated, '_injections', (injection,))
return decorated return decorated
return decorator return decorator

View File

@ -15,15 +15,15 @@ class Provider(object):
"""Base provider class.""" """Base provider class."""
__IS_PROVIDER__ = True __IS_PROVIDER__ = True
__slots__ = ('overridden',) __slots__ = ('_overridden',)
def __init__(self): def __init__(self):
"""Initializer.""" """Initializer."""
self.overridden = None self._overridden = None
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
if self.overridden: if self._overridden:
return self.last_overriding(*args, **kwargs) return self.last_overriding(*args, **kwargs)
return self._provide(*args, **kwargs) return self._provide(*args, **kwargs)
@ -42,47 +42,52 @@ class Provider(object):
def override(self, provider): def override(self, provider):
"""Override provider with another provider.""" """Override provider with another provider."""
if not self.overridden: if not self._overridden:
self.overridden = (ensure_is_provider(provider),) self._overridden = (ensure_is_provider(provider),)
else: else:
self.overridden = self.overridden + (ensure_is_provider(provider),) self._overridden += (ensure_is_provider(provider),)
@property
def is_overridden(self):
"""Check if provider is overridden by another provider."""
return bool(self._overridden)
@property @property
def last_overriding(self): def last_overriding(self):
"""Return last overriding provider.""" """Return last overriding provider."""
try: try:
return self.overridden[-1] return self._overridden[-1]
except (TypeError, IndexError): except (TypeError, IndexError):
raise Error('Provider {0} is not overridden'.format(str(self))) raise Error('Provider {0} is not overridden'.format(str(self)))
def reset_last_overriding(self): def reset_last_overriding(self):
"""Reset last overriding provider.""" """Reset last overriding provider."""
if not self.overridden: if not self._overridden:
raise Error('Provider {0} is not overridden'.format(str(self))) raise Error('Provider {0} is not overridden'.format(str(self)))
self.overridden = self.overridden[:-1] self._overridden = self._overridden[:-1]
def reset_override(self): def reset_override(self):
"""Reset all overriding providers.""" """Reset all overriding providers."""
self.overridden = None self._overridden = None
class Delegate(Provider): class Delegate(Provider):
"""Provider's delegate.""" """Provider's delegate."""
__slots__ = ('delegated',) __slots__ = ('_delegated',)
def __init__(self, delegated): def __init__(self, delegated):
"""Initializer. """Initializer.
:type delegated: Provider :type delegated: Provider
""" """
self.delegated = ensure_is_provider(delegated) self._delegated = ensure_is_provider(delegated)
super(Delegate, self).__init__() super(Delegate, self).__init__()
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
return self.delegated return self._delegated
class Factory(Provider): class Factory(Provider):
@ -92,21 +97,21 @@ class Factory(Provider):
Factory provider creates new instance of specified class on every call. Factory provider creates new instance of specified class on every call.
""" """
__slots__ = ('provides', 'kwargs', 'attributes', 'methods') __slots__ = ('_provides', '_kwargs', '_attributes', '_methods')
def __init__(self, provides, *injections): def __init__(self, provides, *injections):
"""Initializer.""" """Initializer."""
if not isinstance(provides, class_types): if not isinstance(provides, class_types):
raise Error('Factory provider expects to get class, ' + raise Error('Factory provider expects to get class, ' +
'got {0} instead'.format(str(provides))) 'got {0} instead'.format(str(provides)))
self.provides = provides self._provides = provides
self.kwargs = tuple((injection self._kwargs = tuple((injection
for injection in injections for injection in injections
if is_kwarg_injection(injection))) if is_kwarg_injection(injection)))
self.attributes = tuple((injection self._attributes = tuple((injection
for injection in injections for injection in injections
if is_attribute_injection(injection))) if is_attribute_injection(injection)))
self.methods = tuple((injection self._methods = tuple((injection
for injection in injections for injection in injections
if is_method_injection(injection))) if is_method_injection(injection)))
super(Factory, self).__init__() super(Factory, self).__init__()
@ -114,14 +119,14 @@ class Factory(Provider):
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
init_kwargs = dict(((injection.name, injection.value) init_kwargs = dict(((injection.name, injection.value)
for injection in self.kwargs)) for injection in self._kwargs))
init_kwargs.update(kwargs) init_kwargs.update(kwargs)
instance = self.provides(*args, **init_kwargs) instance = self._provides(*args, **init_kwargs)
for attribute in self.attributes: for attribute in self._attributes:
setattr(instance, attribute.name, attribute.value) setattr(instance, attribute.name, attribute.value)
for method in self.methods: for method in self._methods:
getattr(instance, method.name)(method.value) getattr(instance, method.name)(method.value)
return instance return instance
@ -144,23 +149,23 @@ class 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.
""" """
__slots__ = ('instance', 'factory') __slots__ = ('_instance', '_factory')
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Initializer.""" """Initializer."""
self.instance = None self._instance = None
self.factory = Factory(*args, **kwargs) self._factory = Factory(*args, **kwargs)
super(Singleton, self).__init__() super(Singleton, self).__init__()
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
if not self.instance: if not self._instance:
self.instance = self.factory(*args, **kwargs) self._instance = self._factory(*args, **kwargs)
return self.instance return self._instance
def reset(self): def reset(self):
"""Reset instance.""" """Reset instance."""
self.instance = None self._instance = None
class ExternalDependency(Provider): class ExternalDependency(Provider):
@ -171,26 +176,26 @@ class ExternalDependency(Provider):
the client's code, but it's interface is known. the client's code, but it's interface is known.
""" """
__slots__ = ('instance_of',) __slots__ = ('_instance_of',)
def __init__(self, instance_of): def __init__(self, instance_of):
"""Initializer.""" """Initializer."""
if not isinstance(instance_of, class_types): if not isinstance(instance_of, class_types):
raise Error('ExternalDependency provider expects to get class, ' + raise Error('ExternalDependency provider expects to get class, ' +
'got {0} instead'.format(str(instance_of))) 'got {0} instead'.format(str(instance_of)))
self.instance_of = instance_of self._instance_of = instance_of
super(ExternalDependency, self).__init__() super(ExternalDependency, self).__init__()
def __call__(self, *args, **kwargs): def __call__(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
if not self.overridden: if not self._overridden:
raise Error('Dependency is not defined') raise Error('Dependency is not defined')
instance = self.last_overriding(*args, **kwargs) instance = self.last_overriding(*args, **kwargs)
if not isinstance(instance, self.instance_of): if not isinstance(instance, self._instance_of):
raise Error('{0} is not an '.format(instance) + raise Error('{0} is not an '.format(instance) +
'instance of {0}'.format(self.instance_of)) 'instance of {0}'.format(self._instance_of))
return instance return instance
@ -207,16 +212,16 @@ class _StaticProvider(Provider):
it got on input. it got on input.
""" """
__slots__ = ('provides',) __slots__ = ('_provides',)
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 _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
return self.provides return self._provides
class Class(_StaticProvider): class Class(_StaticProvider):
@ -247,14 +252,14 @@ class Callable(Provider):
with some predefined dependency injections. with some predefined dependency injections.
""" """
__slots__ = ('callback', 'injections') __slots__ = ('_callback', '_injections')
def __init__(self, callback, *injections): def __init__(self, callback, *injections):
"""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._injections = tuple((injection
for injection in injections for injection in injections
if is_kwarg_injection(injection))) if is_kwarg_injection(injection)))
super(Callable, self).__init__() super(Callable, self).__init__()
@ -262,10 +267,10 @@ class Callable(Provider):
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
injections = dict(((injection.name, injection.value) injections = dict(((injection.name, injection.value)
for injection in self.injections)) for injection in self._injections))
injections.update(kwargs) injections.update(kwargs)
return self.callback(*args, **injections) return self._callback(*args, **injections)
class Config(Provider): class Config(Provider):
@ -277,13 +282,13 @@ class Config(Provider):
to create deferred config value provider. to create deferred config value provider.
""" """
__slots__ = ('value',) __slots__ = ('_value',)
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 __getattr__(self, item): def __getattr__(self, item):
@ -292,7 +297,7 @@ class Config(Provider):
def _provide(self, paths=None): def _provide(self, paths=None):
"""Return provided instance.""" """Return provided instance."""
value = self.value value = self._value
if paths: if paths:
for path in paths: for path in paths:
try: try:
@ -304,7 +309,7 @@ class Config(Provider):
def update_from(self, value): def update_from(self, value):
"""Update current value from another one.""" """Update current value from another one."""
self.value.update(value) self._value.update(value)
class _ChildConfig(Provider): class _ChildConfig(Provider):
@ -315,19 +320,19 @@ class _ChildConfig(Provider):
the current path in the config tree. the current path in the config tree.
""" """
__slots__ = ('parents', 'root_config') __slots__ = ('_parents', '_root_config')
def __init__(self, parents, root_config): def __init__(self, parents, root_config):
"""Initializer.""" """Initializer."""
self.parents = parents self._parents = parents
self.root_config = root_config self._root_config = root_config
super(_ChildConfig, self).__init__() super(_ChildConfig, self).__init__()
def __getattr__(self, item): def __getattr__(self, item):
"""Return instance of deferred config.""" """Return instance of deferred config."""
return _ChildConfig(parents=self.parents + (item,), return _ChildConfig(parents=self._parents + (item,),
root_config=self.root_config) root_config=self._root_config)
def _provide(self, *args, **kwargs): def _provide(self, *args, **kwargs):
"""Return provided instance.""" """Return provided instance."""
return self.root_config(self.parents) return self._root_config(self._parents)

View File

@ -44,12 +44,12 @@ class ProviderTests(unittest.TestCase):
delegate1 = self.provider.delegate() delegate1 = self.provider.delegate()
self.assertIsInstance(delegate1, Delegate) self.assertIsInstance(delegate1, Delegate)
self.assertIs(delegate1.delegated, self.provider) self.assertIs(delegate1(), self.provider)
delegate2 = self.provider.delegate() delegate2 = self.provider.delegate()
self.assertIsInstance(delegate2, Delegate) self.assertIsInstance(delegate2, Delegate)
self.assertIs(delegate2.delegated, self.provider) self.assertIs(delegate2(), self.provider)
self.assertIsNot(delegate1, delegate2) self.assertIsNot(delegate1, delegate2)
@ -57,7 +57,7 @@ class ProviderTests(unittest.TestCase):
"""Test provider overriding.""" """Test provider overriding."""
overriding_provider = Provider() overriding_provider = Provider()
self.provider.override(overriding_provider) self.provider.override(overriding_provider)
self.assertTrue(self.provider.overridden) self.assertTrue(self.provider.is_overridden)
def test_override_with_not_provider(self): def test_override_with_not_provider(self):
"""Test provider overriding with not provider instance.""" """Test provider overriding with not provider instance."""
@ -98,7 +98,7 @@ class ProviderTests(unittest.TestCase):
self.assertIs(self.provider.last_overriding, overriding_provider1) self.assertIs(self.provider.last_overriding, overriding_provider1)
self.provider.reset_last_overriding() self.provider.reset_last_overriding()
self.assertFalse(self.provider.overridden) self.assertFalse(self.provider.is_overridden)
def test_reset_last_overriding_of_not_overridden_provider(self): def test_reset_last_overriding_of_not_overridden_provider(self):
"""Test resetting of last overriding on not overridden provier.""" """Test resetting of last overriding on not overridden provier."""
@ -109,12 +109,12 @@ class ProviderTests(unittest.TestCase):
overriding_provider = Provider() overriding_provider = Provider()
self.provider.override(overriding_provider) self.provider.override(overriding_provider)
self.assertTrue(self.provider.overridden) self.assertTrue(self.provider.is_overridden)
self.assertIs(self.provider.last_overriding, overriding_provider) self.assertIs(self.provider.last_overriding, overriding_provider)
self.provider.reset_override() self.provider.reset_override()
self.assertFalse(self.provider.overridden) self.assertFalse(self.provider.is_overridden)
try: try:
self.provider.last_overriding self.provider.last_overriding
except Error: except Error: