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?

6
  • Did you try eval()? Commented Mar 7, 2021 at 13:02
  • [eval(i) for i in funcs] ? Commented Mar 7, 2021 at 13:02
  • 2
    How was the list of strings generated? This is an odd thing to want to do and maybe your issue is upstream Commented Mar 7, 2021 at 13:05
  • OK. I didn't know about eval(). It works really fine. Thank you... Commented Mar 7, 2021 at 13:08
  • @BurakBaysal Please beware with this new knowledge. See stackoverflow.com/a/66516837/13552470 Commented Mar 7, 2021 at 13:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware this will evaulate aribrutary code and can be a security risk, e.g. eval('__import__("os").listdir()')
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.