python-dependency-injector/dependency_injector/catalogs.py

358 lines
11 KiB
Python
Raw Normal View History

"""Catalogs module."""
2015-01-04 17:26:33 +03:00
2015-09-01 00:36:26 +03:00
import six
2015-07-17 19:31:44 +03:00
2015-03-13 18:31:07 +03:00
from .errors import Error
2015-07-17 19:31:44 +03:00
from .utils import is_provider
from .utils import is_catalog
2015-11-10 18:58:04 +03:00
from .utils import ensure_is_provider
from .utils import ensure_is_catalog_bundle
2015-07-17 19:31:44 +03:00
@six.python_2_unicode_compatible
class CatalogBundle(object):
"""Bundle of catalog providers."""
catalog = None
""":type: DeclarativeCatalog"""
__IS_CATALOG_BUNDLE__ = True
__slots__ = ('providers', '__dict__')
def __init__(self, *providers):
"""Initializer."""
self.providers = dict()
for provider in providers:
provider_name = self.catalog.get_provider_bind_name(provider)
self.providers[provider_name] = provider
self.__dict__.update(self.providers)
super(CatalogBundle, self).__init__()
@classmethod
def sub_cls_factory(cls, catalog):
"""Create bundle class for catalog.
:rtype: CatalogBundle
:return: Subclass of CatalogBundle
"""
return type('BundleSubclass', (cls,), dict(catalog=catalog))
def get(self, name):
"""Return provider with specified name or raise an error."""
try:
return self.providers[name]
except KeyError:
raise Error('Provider "{0}" is not a part of {1}'.format(name,
self))
def has(self, name):
"""Check if there is provider with certain name."""
return name in self.providers
def __getattr__(self, item):
"""Raise an error on every attempt to get undefined provider."""
if item.startswith('__') and item.endswith('__'):
return super(CatalogBundle, self).__getattr__(item)
raise Error('Provider "{0}" is not a part of {1}'.format(item, self))
def __repr__(self):
"""Return string representation of catalog bundle."""
return '<{0}.Bundle({1})>'.format(
self.catalog.name, ', '.join(six.iterkeys(self.providers)))
__str__ = __repr__
2015-11-10 18:58:04 +03:00
@six.python_2_unicode_compatible
class DynamicCatalog(object):
"""Catalog of providers."""
__IS_CATALOG__ = True
2015-11-11 16:45:39 +03:00
__slots__ = ('name', 'providers', 'provider_names', 'overridden_by',
'Bundle')
2015-11-10 18:58:04 +03:00
def __init__(self, **providers):
2015-11-10 18:58:04 +03:00
"""Initializer.
2015-11-11 16:45:39 +03:00
:type providers: dict[str, dependency_injector.providers.Provider]
2015-11-10 18:58:04 +03:00
"""
self.name = '.'.join((self.__class__.__module__,
self.__class__.__name__))
2015-11-10 18:58:04 +03:00
self.providers = dict()
self.provider_names = dict()
self.overridden_by = tuple()
2015-11-11 16:45:39 +03:00
self.Bundle = CatalogBundle.sub_cls_factory(self)
self.bind_providers(providers)
2015-11-10 18:58:04 +03:00
def is_bundle_owner(self, bundle):
"""Check if catalog is bundle owner."""
return ensure_is_catalog_bundle(bundle) and bundle.catalog is self
def get_provider_bind_name(self, provider):
"""Return provider's name in catalog."""
if not self.is_provider_bound(provider):
raise Error('Can not find bind name for {0} in catalog {1}'.format(
provider, self))
return self.provider_names[provider]
def is_provider_bound(self, provider):
"""Check if provider is bound to the catalog."""
return provider in self.provider_names
def filter(self, provider_type):
"""Return dict of providers, that are instance of provided type."""
return dict((name, provider)
for name, provider in six.iteritems(self.providers)
if isinstance(provider, provider_type))
@property
def is_overridden(self):
"""Check if catalog is overridden by another catalog."""
return bool(self.overridden_by)
@property
def last_overriding(self):
"""Return last overriding catalog."""
try:
return self.overridden_by[-1]
except (TypeError, IndexError):
raise Error('Catalog {0} is not overridden'.format(self))
def override(self, overriding):
"""Override current catalog providers by overriding catalog providers.
:type overriding: DynamicCatalog
"""
self.overridden_by += (overriding,)
for name, provider in six.iteritems(overriding.providers):
2015-11-11 16:45:39 +03:00
self.get_provider(name).override(provider)
2015-11-10 18:58:04 +03:00
def reset_last_overriding(self):
"""Reset last overriding catalog."""
if not self.is_overridden:
raise Error('Catalog {0} is not overridden'.format(self))
self.overridden_by = self.overridden_by[:-1]
for provider in six.itervalues(self.providers):
provider.reset_last_overriding()
def reset_override(self):
"""Reset all overridings for all catalog providers."""
self.overridden_by = tuple()
for provider in six.itervalues(self.providers):
provider.reset_override()
2015-11-11 16:45:39 +03:00
def get_provider(self, name):
2015-11-10 18:58:04 +03:00
"""Return provider with specified name or raise an error."""
try:
return self.providers[name]
except KeyError:
raise Error('{0} has no provider with such name - {1}'.format(
self, name))
2015-11-11 16:45:39 +03:00
def bind_provider(self, name, provider):
"""Bind provider to catalog with specified name."""
provider = ensure_is_provider(provider)
if name in self.providers:
raise Error('Catalog {0} already has provider with '
'such name - {1}'.format(self, name))
if provider in self.provider_names:
raise Error('Catalog {0} already has such provider '
'instance - {1}'.format(self, provider))
self.providers[name] = provider
self.provider_names[provider] = name
def bind_providers(self, providers):
"""Bind providers dictionary to catalog."""
for name, provider in six.iteritems(providers):
self.bind_provider(name, provider)
def has_provider(self, name):
2015-11-10 18:58:04 +03:00
"""Check if there is provider with certain name."""
return name in self.providers
2015-11-11 16:45:39 +03:00
def __getattr__(self, name):
"""Return provider with specified name or raise en error."""
return self.get_provider(name)
2015-11-10 18:58:04 +03:00
def __repr__(self):
"""Return Python representation of catalog."""
2015-11-11 16:45:39 +03:00
return '<{0}({1})>'.format(self.name,
', '.join(six.iterkeys(self.providers)))
2015-11-10 18:58:04 +03:00
__str__ = __repr__
2015-11-04 17:32:04 +03:00
@six.python_2_unicode_compatible
class DeclarativeCatalogMetaClass(type):
"""Declarative catalog meta class."""
2015-07-17 19:31:44 +03:00
def __new__(mcs, class_name, bases, attributes):
"""Declarative catalog class factory."""
2015-10-14 17:51:05 +03:00
cls = type.__new__(mcs, class_name, bases, attributes)
2015-11-10 16:15:48 +03:00
cls_providers = tuple((name, provider)
for name, provider in six.iteritems(attributes)
if is_provider(provider))
inherited_providers = tuple((name, provider)
for base in bases if is_catalog(base)
for name, provider in six.iteritems(
base.providers))
providers = cls_providers + inherited_providers
2015-10-15 20:15:38 +03:00
2015-11-10 18:58:04 +03:00
cls.name = '.'.join((cls.__module__, cls.__name__))
2015-11-11 16:45:39 +03:00
cls.catalog = DynamicCatalog()
cls.catalog.name = cls.name
2015-11-11 16:45:39 +03:00
cls.catalog.bind_providers(dict(providers))
2015-11-10 16:15:48 +03:00
cls.cls_providers = dict(cls_providers)
cls.inherited_providers = dict(inherited_providers)
2015-10-14 17:51:05 +03:00
2015-11-11 16:45:39 +03:00
cls.Bundle = cls.catalog.Bundle
2015-10-14 17:51:05 +03:00
return cls
2015-01-04 17:26:33 +03:00
2015-11-10 18:58:04 +03:00
@property
def providers(cls):
"""Return dict of catalog's providers."""
return cls.catalog.providers
@property
def overridden_by(cls):
"""Return tuple of overriding catalogs."""
return cls.catalog.overridden_by
2015-10-16 23:54:51 +03:00
@property
def is_overridden(cls):
"""Check if catalog is overridden by another catalog."""
2015-11-10 18:58:04 +03:00
return cls.catalog.is_overridden
@property
def last_overriding(cls):
"""Return last overriding catalog."""
2015-11-10 18:58:04 +03:00
return cls.catalog.last_overriding
2015-10-11 15:34:21 +03:00
def __repr__(cls):
2015-11-10 18:58:04 +03:00
"""Return string representation of the catalog."""
return '<DeclarativeCatalog {0}>'.format(cls.name)
2015-11-04 17:32:04 +03:00
__str__ = __repr__
2015-10-11 15:34:21 +03:00
2015-01-04 17:26:33 +03:00
@six.add_metaclass(DeclarativeCatalogMetaClass)
class DeclarativeCatalog(object):
"""Declarative catalog catalog of providers.
2015-11-10 18:58:04 +03:00
:type name: str
:param name: Catalog's name
:type catalog: DynamicCatalog
:param catalog: Instance of dynamic catalog
:type Bundle: CatalogBundle
:param Bundle: Catalog's bundle class
:type providers: dict[str, dependency_injector.Provider]
:param providers: Dict of all catalog providers, including inherited from
parent catalogs
:type cls_providers: dict[str, dependency_injector.Provider]
:param cls_providers: Dict of current catalog providers
:type inherited_providers: dict[str, dependency_injector.Provider]
:param inherited_providers: Dict of providers, that are inherited from
parent catalogs
2015-10-15 20:15:38 +03:00
:type overridden_by: tuple[DeclarativeCatalog]
:param overridden_by: Tuple of overriding catalogs
:type is_overridden: bool
:param is_overridden: Read-only, evaluated in runtime, property that is
set to True if catalog is overridden
:type last_overriding: DeclarativeCatalog | None
:param last_overriding: Reference to the last overriding catalog, if any
"""
2015-07-17 19:31:44 +03:00
2015-11-10 18:58:04 +03:00
name = str()
catalog = DynamicCatalog
2015-10-16 23:54:51 +03:00
Bundle = CatalogBundle
2015-10-15 20:15:38 +03:00
cls_providers = dict()
inherited_providers = dict()
2015-10-15 20:15:38 +03:00
providers = dict()
2015-01-04 17:26:33 +03:00
overridden_by = tuple()
is_overridden = bool
last_overriding = None
__IS_CATALOG__ = True
@classmethod
def is_bundle_owner(cls, bundle):
"""Check if catalog is bundle owner."""
2015-11-10 18:58:04 +03:00
return cls.catalog.is_bundle_owner(bundle)
@classmethod
def get_provider_bind_name(cls, provider):
"""Return provider's name in catalog."""
2015-11-10 18:58:04 +03:00
return cls.catalog.get_provider_bind_name(provider)
@classmethod
def is_provider_bound(cls, provider):
"""Check if provider is bound to the catalog."""
2015-11-10 18:58:04 +03:00
return cls.catalog.is_provider_bound(provider)
2015-01-11 19:10:11 +03:00
@classmethod
2015-07-17 19:31:44 +03:00
def filter(cls, provider_type):
"""Return dict of providers, that are instance of provided type."""
2015-11-10 18:58:04 +03:00
return cls.catalog.filter(provider_type)
2015-01-11 19:10:11 +03:00
@classmethod
2015-03-12 13:45:15 +03:00
def override(cls, overriding):
2015-07-06 16:52:51 +03:00
"""Override current catalog providers by overriding catalog providers.
2015-01-11 19:10:11 +03:00
2015-11-10 18:58:04 +03:00
:type overriding: DeclarativeCatalog | DynamicCatalog
2015-01-11 19:10:11 +03:00
"""
2015-11-10 18:58:04 +03:00
cls.catalog.override(overriding)
@classmethod
def reset_last_overriding(cls):
"""Reset last overriding catalog."""
2015-11-10 18:58:04 +03:00
cls.catalog.reset_last_overriding()
@classmethod
def reset_override(cls):
"""Reset all overridings for all catalog providers."""
2015-11-10 18:58:04 +03:00
cls.catalog.reset_override()
2015-10-11 15:34:21 +03:00
@classmethod
def get(cls, name):
"""Return provider with specified name or raises error."""
2015-11-11 16:45:39 +03:00
return cls.catalog.get_provider(name)
2015-10-11 15:34:21 +03:00
@classmethod
def has(cls, name):
"""Check if there is provider with certain name."""
2015-11-11 16:45:39 +03:00
return cls.catalog.has_provider(name)
2015-10-11 15:34:21 +03:00
# Backward compatibility for versions < 0.11.*
AbstractCatalog = DeclarativeCatalog
def override(catalog):
"""Catalog overriding decorator."""
def decorator(overriding_catalog):
"""Overriding decorator."""
catalog.override(overriding_catalog)
return overriding_catalog
return decorator