My app allows the user to specify simple python expressions to use as functions of a given variable. For example, the user could write 'x**2 + 2*x + 4' and my app would parse that into a function of x, equivalent to lambda x: x**2 + 2*x + 4. I already know how to do this with:
def _f(expression, template):
code = parser.expr(expression).compile()
return template(code)
def function_x(expression):
return _f(expression, lambda code: lambda x: eval(code))
However, that only makes a function parser for x. If I want to make a different variable work, I would have to define more parsers, like:
def function_xy(expression):
return _f(expression, lambda code: lambda x, y: eval(code))
def function_n(expression):
return _f(expression, lambda code: lambda n: eval(code))
def function_A(expression):
return _f(expression, lambda code: lambda A: eval(code))
Is there any better way to parse user functions of any pre-specified variable? That is to say, I can predefine a certain input field in the UI to accept functions of u, while predefining another input field to accept functions of v, and so forth. Only the letter u would work in the first input field, while only the letter v would work in the second.
Please note that the variable names themselves are predefined; the user does not pick which letters he or she wants to use.