Python 内建函数 - eval(expression, globals=None, locals=None)

Python 的内置函数 `eval()` 用于执行一个字符串表达式,并返回表达式的值。它接受一个字符串参数和可选的全局及局部字典,用于解析和执行表达式。如果全局字典缺少 'builtins',当前全局环境会被复制到全局字典中。`eval()` 可用于执行代码对象,当模式为 'exec' 时,返回值为 `None`。注意安全问题,可以使用 `ast.literal_eval()` 安全地评估只包含字面量的表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

拓展阅读

compile()
exec()
globals()
locals()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值