Reputation: 11
I have a list of strings which contains lambda functions like this:
funcs = ["lambda x: x * x", "lambda x: x + x"]
And I want to use these functions as we use lambda. If I had this for example:
funcs = [lambda x: x * x, lambda x: x + x]
a = funcs[0](3)
print(a)
> 9
But first I need to convert this string to a lambda
to use it as lambda
. How will I do that?
Upvotes: 0
Views: 1248
Reputation: 86
You can use the eval
builtin function, see the part of the docs about it
For instance:
funcs = ["lambda x: x * x", "lambda x: x + x"]
funcs = [eval(func_str) for func_str in funcs]
However, keep in mind that the use of eval
is a security risk and therefore, in order to prevent code injection, you need to make sure that the strings do not come from user input or that the usage scope of the script is private
Upvotes: 3
Reputation: 27577
WARNING: The eval()
method is really dangerous, so please don't do this. See here: Why is using 'eval' a bad practice?
At your own risk, you can use the eval()
method to evaluate a string as code:
funcs = ["lambda x: x * x", "lambda x: x + x"]
funcs = list(map(eval, funcs))
a = funcs[0](3)
print(a)
Output:
9
The line list(map(eval, funcs))
uses the built-in map()
method to map the eval()
method to each string in the array.
There's also this neat article on the topic: Eval really is dangerous
Upvotes: 1