I am creating a method that constructs an anonymous method to return a function of multiple variables e.g. f(x, y, z) = b. I want the user to be able to pass a list of variables:
def get_multivar_lambda(expression, variables=["x"])
I then want the returned anonymous function to take exactly len(variables)
arguments (either positional based on their list index or keyword based on the string in the list). I know I can use *args
and check the length, but this seems inelegant.
Is this possible? How might I do this?
Here is an example of how I did it for one variable (where seval
is a from module simple_eval
):
def get_lambda(expression, variable="x"):
return lambda arg: seval(expression.replace(variable, str(arg)))
And here's how I did it by just checking the length of the arguments*
passed:
def get_multivar_lambda(expression, variables=["x"]):
def to_return(*arguments):
if len(variables) != len(arguments):
raise Exception("Number of arguments != number of variables")
for v, a in zip(variables, arguments):
expression.replace(v, a)
return seval(expression)
return to_return
EDIT: I am taking expression and variables from user input, so a safe way to do this would be best.