[config] Implements a "requires()" service injection decorator for functions (api may change).

This commit is contained in:
Romain Dorgueil
2017-06-17 08:02:29 +02:00
parent b8125ea579
commit 8c898afc27
2 changed files with 24 additions and 3 deletions

View File

@ -1,7 +1,7 @@
from bonobo.config.configurables import Configurable
from bonobo.config.options import Option, Method
from bonobo.config.options import Method, Option
from bonobo.config.processors import ContextProcessor
from bonobo.config.services import Container, Service, Exclusive
from bonobo.config.services import Container, Exclusive, Service, requires
# bonobo.config public programming interface
__all__ = [
@ -12,4 +12,5 @@ __all__ = [
'Method',
'Option',
'Service',
'requires',
]

View File

@ -56,7 +56,11 @@ class Service(Option):
inst.__options_values__[self.name] = validate_service_name(value)
def resolve(self, inst, services):
return services.get(getattr(inst, self.name))
try:
name = getattr(inst, self.name)
except AttributeError:
name = self.name
return services.get(name)
class Container(dict):
@ -126,3 +130,19 @@ class Exclusive(ContextDecorator):
def __exit__(self, *exc):
self.get_lock().release()
def requires(*service_names):
def decorate(mixed):
try:
options = mixed.__options__
except AttributeError:
mixed.__options__ = options = {}
for service_name in service_names:
service = Service(service_name)
service.name = service_name
options[service_name] = service
return mixed
return decorate