0

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?

Red
  • 26,798
  • 7
  • 36
  • 58

2 Answers2

3

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

  • 2
    Be aware this will evaulate aribrutary code and can be a security risk, e.g. `eval('__import__("os").listdir()')` – Chris_Rands Mar 07 '21 at 13:08
1

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

Red
  • 26,798
  • 7
  • 36
  • 58