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?
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.