我现在两次遇到这个问题,最后提出了一个安全且不难看的解决方案(以我的拙见)。
回顾以前的答案:
全局变量是一种易于使用,快速且简便的方法,但是您必须与函数名称超级一致,并且如果变量被覆盖,它可能会在运行时中断。 也是非Python的,不安全的,不道德的,yadda yadda ...
字典(即字符串到函数的映射)更安全且易于使用...但是让我无休止地困扰我,因为我不得不将字典分配分散到我的文件中,这很容易引起人们的注意。
装饰者为我准备了词典解决方案。 装饰器是将副作用和转换附加到函数定义的一种不错的方法。
时间示例
fields = ['name', 'email', 'address']
# set up our function dictionary
cleaners = {}
# this function will add stuff into the dictionary
def add_cleaner(key):
# this is a parametered decorator, it returns the actual decorator
def actual_decorator(func):
# add func to the dictionary
cleaners[key] = func
return func
return actual_decorator
每当您定义清洁器函数时,请将其添加到声明中:
@add_cleaner('email')
def email_cleaner(email):
#do stuff here
return result
这些函数在解析后立即添加到字典中,可以这样调用:
cleaned_email = cleaners['email'](some_email)
您可能想要在脚本的底部添加这一行,以确保您不会忘记这一行。 ;)
assert(set(cleaners.keys()).issubset(fields))