简体   繁体   English

how to convert a string object to a lambda function object in python

[英]how to convert a string object to a lambda function object in python

I have a list of strings which contains lambda functions like this:我有一个字符串列表,其中包含 lambda 函数,如下所示:

funcs = ["lambda x: x * x", "lambda x: x + x"]

And I want to use these functions as we use lambda.我想使用这些功能,因为我们使用 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 .但首先我需要将此字符串转换为lambda以将其用作lambda How will I do that?我将如何做到这一点?

You can use the eval builtin function, see the part of the docs about it您可以使用eval内置 function,请参阅有关它的文档部分

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但是请记住,使用eval存在安全风险,因此,为了防止代码注入,您需要确保字符串不是来自用户输入,或者脚本的使用 scope 是私有的

WARNING: The eval() method is really dangerous, so please don't do this.警告: eval()方法非常危险,所以请不要这样做。 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:您可以自行承担风险,使用eval()方法将字符串评估为代码:

funcs = ["lambda x: x * x", "lambda x: x + x"]
funcs = list(map(eval, funcs))
a = funcs[0](3)
print(a)

Output: 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.list(map(eval, funcs)) funcs)) 对数组中的每个字符串使用内置的map()方法 map eval()方法。


There's also this neat article on the topic: Eval really is dangerous还有这篇关于该主题的简洁文章: Eval 真的很危险

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM