在Python中使用eval? [英] Use of eval in Python?

查看:56
本文介绍了在Python中使用eval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩耍时偶然发现的Python中有一个 eval()函数。我想不出需要此功能的情况,除了可能是语法糖。有人可以举个例子吗?

There is an eval() function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?

推荐答案

eval exec 是方便快捷的方法,可以动态获取一些源代码,也许要稍加修改然后再执行-但是,它们从来都不是最好的方法,尤其是在生产中代码而不是快速而肮脏的原型& c。

eval and exec are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.

例如,如果我必须处理这种动态Python源代码, ast 模块- ast.literal_eval eval 安全得多(如果它是一次性的并且仅依赖简单常量,则可以直接以表达式的字符串形式调用它) ,或者先执行 node = ast.parse(source),然后保留 node 左右,也许用适当的方法对其进行修补访问者,例如进行变量查找,然后是 literal_eval 节点)-或一旦将节点置于适当的形状并对其进行了安全发行审核es,我可以编译它(产生一个代码对象),并以此构建一个新的函数对象。远没有那么简单(除了 ast.literal_eval eval 一样简单!),但更安全且

For example, if I had to deal with such dynamic Python sources, I'd reach for the ast module -- ast.literal_eval is MUCH safer than eval (you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do node = ast.parse(source) first, then keep the node around, perhaps munge it with suitable visitors e.g. for variable lookup, then literal_eval the node) -- or, once having put the node in proper shape and vetted it for security issues, I could compile it (yielding a code object) and build a new function object out of that. Far less simple (except that ast.literal_eval is just as simple as eval for the simplest cases!) but safer and preferable in production-quality code.

对于许多任务,我见过人们(ab-)使用 exec eval ,例如Python的强大内置函数,例如 getattr setattr globals()和& c的$ c>提供了更可取的且实际上通常更简单的解决方案。对于解析JSON之类的特定用途,使用 json 之类的库模块更好(例如,请参见SilentGhost对耳鸣的评论)。等等...

For many tasks I've seen people (ab-)use exec and eval for, Python's powerful built-ins, such as getattr and setattr, indexing into globals(), &c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as json are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc...

这篇关于在Python中使用eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆