I am trying to write a feature where an user will enter the function logic and my framework will create a plugin from it ready for execution. I cannot use lamda functions since they only evaluate to single expressions and limits the scope of the user defined functions.
I am trying to solve this by giving a defined function template to the user which contains some specific function names. The user populates the template and I use the exec
statement to integrate the code.
Here is the function template:
def rule(output):
pass
The user populates the template like this:
def rule(output):
return True if 'PSU' in output else False
The way I am implementing this is like this:
>>> code = """def rule(output):
return True if 'PSU' in output else False
"""
>>> exec(code)
>>> print(rule)
>>> print(rule('RACPSU: Y'))
True
This is working as expected. However when I am using the same logic inside a class, it is not working.
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())
This gives the error: NameError: name 'rule' is not defined
Please give any ideas on how to fix this