Manual
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘builtins’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>>
>>> x = 1
>>> eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with ‘exec’ as the mode argument, eval()‘s return value will be None.
Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.
直译
参数expression为字符串,globals和locals为可选参数,如果提供,globals必须是字典,locals可以是任意映射对象。
expression参数解析后相当于Python表达式(技术上讲是一个条件列表),使用globals和locals字典作为全局和局部域名。如果给出globals字典但缺省‘builtins’,则在表达式解析前会将当前全局变量拷贝至globals,这意味着expression一般完全访问标准内建模块,并且传递严格限制的环境。如果locals字典缺省,它默认指向globals字典。如果两个字典都缺省,则在调用eval()的环境下执行表达式,返回值为等价表达式的结果值,语法错误将会报告异常。实例:
>>>
>>> x = 1
>>> eval('x+1')
2
该函数也被用于执行任意代码对象(像那些由compile()所创建的),这种情况下,用传入代码对象来替代字符串。如果代码对象已经由mode参数’exec’进行编译,那么eval()的返回值将会是None。
建议:exec()函数支持语句的动态执行,globals()和locals()函数各自返回当前全局和局部字典,这可能对使用eval()或exec()时的参数传入有帮助。
实例
# compile()编译
>>> ex = '12 % 5'
>>> c_ex = compile(ex, '', 'eval')
>>> eval(c_ex)
2