python-dependency-injector/objects/catalog.py

72 lines
1.8 KiB
Python
Raw Normal View History

2015-01-04 17:26:33 +03:00
"""
Catalog module.
"""
2015-01-11 16:03:45 +03:00
from .providers import Provider
2015-01-04 17:26:33 +03:00
class AbstractCatalog(object):
2015-01-04 17:26:33 +03:00
"""
Abstract object provides catalog.
2015-01-04 17:26:33 +03:00
"""
def __init__(self, *used_providers):
"""
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-01-04 17:26:33 +03:00
"""
2015-01-11 19:10:11 +03:00
Returns providers.
2015-01-04 17:26:33 +03:00
2015-01-11 19:10:11 +03:00
:param item:
2015-01-04 17:26:33 +03:00
:return:
"""
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 AttributeError('Provider \'{}\' is not listed in '
'dependencies'.format(item))
return attribute
@classmethod
def __all_providers__(cls, provider_type=Provider):
2015-01-11 19:10:11 +03:00
"""
Returns set of all class providers.
"""
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
def __override___(cls, overriding):
"""
Overrides current catalog providers by overriding catalog providers.
:param overriding: AbstractCatalog
2015-01-11 19:10:11 +03:00
"""
overriden = overriding.__all_providers__() - cls.__all_providers__()
for name, provider in overriden:
overridden_provider = getattr(cls, name)
overridden_provider.__override__(provider)
def overrides(catalog):
"""
Catalog overriding decorator.
:param catalog:
:return:
"""
def decorator(overriding_catalog):
catalog.__override___(overriding_catalog)
return overriding_catalog
return decorator