我正在尝试编写一个功能,用户可以输入功能逻辑,而我的框架将通过该功能创建一个插件,以供执行。 我不能使用lamda函数,因为它们仅求值单个表达式并限制了用户定义函数的范围。
我正在尝试通过向用户提供一个包含一些特定功能名称的已定义功能模板来解决此问题。用户填充模板,我使用exec
语句集成代码。
这是功能模板:
def rule(output):
pass
用户按如下所示填充模板:
def rule(output):
return True if 'PSU' in output else False
我实现此方法的方式如下:
>>> code = """def rule(output):
return True if 'PSU' in output else False
"""
>>> exec(code)
>>> print(rule)
>>> print(rule('RACPSU: Y'))
True
这按预期工作。但是,当我在类中使用相同的逻辑时,它将无法正常工作。
class Condition:
def __init__(self, code_str):
pass
def __call__(self, *args, **kwargs):
code = """def rule(output):
return True if 'PSU' in output else False
"""
exec(code)
print(rule)
if __name__ == '__main__':
c1 = Condition('')
print(c1())
这给出了错误:NameError: name 'rule' is not defined
请提供有关如何解决此问题的想法