Python内置函数(19)——eval
英文文档:
eval(expression, globals=None, locals=None)- 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
builtinsmodule 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 whereeval()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. Theglobals()andlocals()functions returns the current global and local dictionary, respectively, which may be useful to pass around for use byeval()orexec(). - See
ast.literal_eval()for a function that can safely evaluate strings with expressions containing only literals. - 说明:
- 1. 执行动态语句,返回语句执行的值。
>>> eval('1+2+3+4')
10
2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。
3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量。
>>> g = {'num':2}
>>> eval('num + 2') #num未定义
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num + 2')
File "<string>", line 1, in <module>
NameError: name 'num' is not defined
>>> eval('num + 2',g) #g中有定义num,可执行
4
4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量
>>> g = {'num1':2}
>>> l = {'num2':4}
>>> eval('num1+num2',g,l)
6
5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。
>>> g = {}
>>> eval('abs(-1)',g)
1
>>> g = {'__builtins__':{}}
>>> eval('abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval('abs(-1)',g)
File "<string>", line 1, in <module>
NameError: name 'abs' is not defined
6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。
>>> num = 1
>>> eval('num+2')
3 >>> globals() #返回字典中含有num的key
{'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>} >>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num+2',{})
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> l = locals()
>>> eval('num+2',{},l) #locals参数含有num的key,能求值
3 >>> locals()
{'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>>
Python内置函数(19)——eval的更多相关文章
- python 内置函数input/eval(22)
python的内置函数其实挺多的,其中input和eval算得上比较特殊,input属于交互式内置函数,eval函数能直接执行字符串表达式并返回表达式的值. 一.input函数 input是Pytho ...
- Python内置函数(61)——eval
英文文档: eval(expression, globals=None, locals=None) The arguments are a string and optional globals an ...
- Python内置函数(19)——oct
英文文档: oct(x) Convert an integer number to an octal string. The result is a valid Python expression. ...
- Python内置函数(19)-slice
官方文档 class slice(stop) class slice(start, stop[, step]) Return a slice object representing the set o ...
- Python内置函数之eval()
eval(expression,globals=None,locals=None) 返回表达式的值.第一个参数必须是字符串.第二个参数可选,如果有必须是字典:第三个参数可选,如果有必须是映射对象(比如 ...
- python内置函数,匿名函数
一.匿名函数 匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n ...
- Python之路(第八篇)Python内置函数、zip()、max()、min()
一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算,如果全部都是true,就返回true, 但是如果是空字符串.空列表也返回t ...
- Python之路Python内置函数、zip()、max()、min()
Python之路Python内置函数.zip().max().min() 一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算, ...
- python内置函数简单归纳
做python小项目的时候发现熟练运用python内置函数,可以节省很多的时间,在这里整理一下,便于以后学习或者工作的时候查看.函数的参数可以在pycharm中ctrl+p查看. 1.abs(x):返 ...
随机推荐
- 分支界定( BRANCH-AND-BOUND)
分支定界法(branch and bound)是一种求解整数规划问题的最常用算法.这种方法不但可以求解纯整数规划,还可以求解混合整数规划问题.分支定界法是一种搜索与迭代的方法,选择不同的分支变量和子问 ...
- JMeter调试参数是否取值正确,调试正则提取的结果(log.info|log.error|print)
JMeter调试参数是否取值正确,调试正则提取的结果(log.info | log.error | print) Jmeter的log输出控制(jmeter.log) 1 2 log_level.jm ...
- HTTP/2部署使用
为了更好地研究HTTP2的一些新特性,或者有小伙伴想让自己的站点支持HTTP2的请求,以提升访问性能……无论出于什么目的,我们都有必要尝试将HTTP2部署使用. 而刚好,我们前一段时间在做HTTP2的 ...
- C++ MD5类封装
c++ md5 算法封装 md5.h #ifndef MD5_H #define MD5_H #include <string> #include <fstream> /* T ...
- mstsc的事 随笔
当个备份吧, 记不得了,就翻一下自己的博客. MSTSC 设置, 平台:Windows 10 企业版 Windows 10 企业版,功能最全.
- mysql5.7.X版本only_full_group_by问题解决
一.出错原因 最近因为开发数据库与部署数据库版本不同,带来了几个问题,其中only_full_group_by问题是之前没有遇到的. 具体报错如下 [Err] 1055 - Expression #1 ...
- GDKOI2017滚粗记
Preface 比赛成绩非常烂,却腐败得非常爽,但是gmh大爷因为和我们腐败,变得更强. 比赛策略有点问题,拼命想正解而没了暴力分 数论题做得比较少,导致只会找规律.知识点需要补充,如AC自动机,启发 ...
- vue事件修饰符
阻止单击事件冒泡 <a v-on:click.stop="doThis"></a>提交事件不再重载页面<form v-on:submit.preven ...
- echarts-for-react 从新渲染数据
<ReactEcharts option={option} notMerge={true} style={{height: '600px', width: '100%'}} className ...
- for循环:用turtle画一颗五角星
import turtle # 设置初始位置 turtle.penup() turtle.left(90) turtle.fd(200) turtle.pendown() turtle.right(9 ...