Last active
September 29, 2019 16:16
-
-
Save RoySegall/d8182fd16acd801f52c644dab195fca3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
from abc import abstractmethod | |
class BaseService: | |
@abstractmethod | |
def info(self): | |
return 'this is the base service' | |
class Service(BaseService): | |
def info(self): | |
return 'this is the service' | |
class HttpService(BaseService): | |
def info(self): | |
return 'this is the Http Service' | |
class OrmService(BaseService): | |
def info(self): | |
return 'this is the Orm Service' | |
def injectable(func): | |
def list_of_services(): | |
return { | |
'http_service': HttpService(), | |
'orm_service': OrmService(), | |
} | |
def inner(*args, **kwargs): | |
arguments = inspect.getfullargspec(func).args | |
for arg in arguments: | |
# Get the base service. | |
if arg == 'service': | |
kwargs['service'] = Service() | |
continue | |
# Try to get a service from a predefined list of services. | |
if arg in list_of_services(): | |
kwargs[arg] = list_of_services()[arg] | |
continue | |
func(*args, **kwargs) | |
return inner | |
@injectable | |
def very_important_function(simple_variable, http_service, orm_service): | |
print(simple_variable) | |
print(orm_service.info()) | |
print(http_service.info()) | |
# Will output: | |
# this is a simple variable | |
# this is the Orm Service | |
# this is the Http Service | |
very_important_function("this is a simple variable") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment