python-dependency-injector/objects/catalog.py

59 lines
1.8 KiB
Python
Raw Normal View History

2015-03-09 01:01:39 +03:00
"""Catalog module."""
2015-01-04 17:26:33 +03:00
2015-01-11 16:03:45 +03:00
from .providers import Provider
2015-03-13 18:31:07 +03:00
from .errors import Error
2015-01-04 17:26:33 +03:00
class AbstractCatalog(object):
2015-03-09 01:01:39 +03:00
"""Abstract object provides catalog."""
2015-01-04 17:26:33 +03:00
__slots__ = ('__used_providers__',)
2015-01-04 17:26:33 +03:00
def __init__(self, *used_providers):
2015-03-09 01:01:39 +03:00
"""Initializer."""
2015-01-11 19:10:11 +03:00
self.__used_providers__ = set(used_providers)
2015-01-04 17:26:33 +03:00
2015-01-11 19:10:11 +03:00
def __getattribute__(self, item):
2015-03-09 01:01:39 +03:00
"""Return providers."""
attribute = super(AbstractCatalog, self).__getattribute__(item)
2015-01-11 19:10:11 +03:00
if item in ('__used_providers__',):
return attribute
if attribute not in self.__used_providers__:
raise Error('Provider \'{0}\' '.format(item) +
2015-03-13 18:31:07 +03:00
'is not listed in dependencies')
2015-01-11 19:10:11 +03:00
return attribute
@classmethod
2015-03-12 13:45:15 +03:00
def all_providers(cls, provider_type=Provider):
2015-03-09 01:01:39 +03:00
"""Return set of all class providers."""
2015-01-11 19:10:11 +03:00
providers = set()
for attr_name in set(dir(cls)) - set(dir(AbstractCatalog)):
2015-01-11 19:10:11 +03:00
provider = getattr(cls, attr_name)
if not isinstance(provider, provider_type):
2015-01-04 17:26:33 +03:00
continue
2015-01-11 19:10:11 +03:00
providers.add((attr_name, provider))
return providers
@classmethod
2015-03-12 13:45:15 +03:00
def override(cls, overriding):
2015-01-11 19:10:11 +03:00
"""
2015-03-09 01:01:39 +03:00
Override current catalog providers by overriding catalog providers.
2015-01-11 19:10:11 +03:00
:param overriding: AbstractCatalog
2015-01-11 19:10:11 +03:00
"""
2015-03-12 13:45:15 +03:00
overridden = overriding.all_providers() - cls.all_providers()
2015-03-09 01:01:39 +03:00
for name, provider in overridden:
2015-01-11 19:10:11 +03:00
overridden_provider = getattr(cls, name)
2015-03-12 13:45:15 +03:00
overridden_provider.override(provider)
2015-01-11 19:10:11 +03:00
def override(catalog):
2015-03-09 01:01:39 +03:00
"""Catalog overriding decorator."""
2015-01-11 19:10:11 +03:00
def decorator(overriding_catalog):
2015-03-10 01:43:23 +03:00
"""Overriding decorator."""
2015-03-12 13:45:15 +03:00
catalog.override(overriding_catalog)
2015-01-11 19:10:11 +03:00
return overriding_catalog
return decorator