1

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

  • 2
    Possible duplicate of [Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3](https://stackoverflow.com/questions/25076883/creating-dynamically-named-variables-in-a-function-in-python-3-understanding-e) – Aran-Fey Oct 18 '18 at 06:30
  • can't reproduce the error... after fixing the indentation errors it works without exception.... – AntiMatterDynamite Oct 18 '18 at 12:19
  • @AntiMatterDynamite Are you using Python 3.6 . Can you run the last code block and show me the ouput? – Shubho Ganguly Oct 21 '18 at 03:24

0 Answers0