我试图让我的代码库中的函数可以通过唯一标识符调用,为此我创建了一个注册函数的装饰器
global FUNCTION_REGISTRY
FUNCTION_REGISTRY = {}
class FunctionAlreadyRegistered(Exception):
pass
def register_function(function_identifier, function):
global FUNCTION_REGISTRY
if function_identifier not in FUNCTION_REGISTRY:
FUNCTION_REGISTRY[function_identifier] = function
else:
raise FunctionAlreadyRegistered
def call_registered_function(function_identifier, *args, **kwargs):
global FUNCTION_REGISTRY
if function_identifier in FUNCTION_REGISTRY:
FUNCTION_REGISTRY[function_identifier](*args, **kwargs)
class EventHandler(object):
def __init__(self, identifier):
self.identifier = identifier
def __call__(self, original_func):
decorator_self = self
def wrappee(*args, **kwargs):
original_func(*args, **kwargs)
print "REGISTER FUNCTION", decorator_self.identifier
register_function(decorator_self.identifier, wrappee)
return wrappee
然后我像这样应用这个装饰
@EventHandler(identifier="something.task-created-handler")
def task_created_event_handler(pk=None, *args, **kwargs):
pass
这使我可以轻松地执行以下操作
call_registered_function("something.task-created-handler",argument="value")
然而,只有在其他文件故意导入此文件时才会评估此装饰器,我想通过我的代码库评估所有这些装饰器以注册所有已识别的函数
当运行时以无缝方式启动时,有没有办法让python评估所有这些装饰器?