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):返 ...
随机推荐
- HeadFirst学习笔记-2.观察者(Observer)模式
认识观察者模式 我们用报纸和杂志的订阅为例来介绍: 报社的业务就是出版报纸. 向某家报社订阅报纸,只要他们有新报纸出版,就会给你送来.只要你是他们的订户,你就会一直收到新报纸. 当你不想再看报纸的时候 ...
- Redis 缓存失效和回收机制
本文及后续文章,Redis版本均是v3.2.8 一.内存回收策略 maxmemory配置用于配置Redis存储数据时指定限制的内存大小.我们可以通过redis.conf配置或者使用CONFIG SET ...
- linux上部署JMeter
export JAVA_HOME=/opt/jdk1.8.0_171 export PATH=$PATH:$JAVA_HOME/bin 让环境变量生效 vi /etc/profile 添加下述两行: ...
- Excel—工作常用
上周起始日期 =TODAY()-WEEKDAY(TODAY(),2)-6 TODAY()表示的是当天的日期,WEEKDAY(TODAY(),2)表示本周的星期几,TODAY()-WEEKDAY(TOD ...
- 洛谷p1106 删数问题 题解
传送门 # 4.24一个重要的日子.我人生中第一道7个测试点下载了5个的题目被我发现了,第一次用光下载数据点机会,真心坑点重重. 这题是一道很经典的贪心题目,可能是因为我太蒻了,导致我一直以为最少普及 ...
- 用DFS求连通块(种子填充)
[问题] 输入一个m行n列的字符矩阵,统计字符“@”组成多少个八连块.如果两个字符“@”所在的格子相邻(横.竖或者对角线方向),就说它们属于同一个八连块.例如,图6-9中有两个八连块. 图6-9 [分 ...
- WPF RadioButton的绑定
1. 枚举类 public enum EnumDataTypes { Simulation, Test } 2. 枚举型与布尔型的转换 public class EnumToBooleanConver ...
- 展开被 SpringBoot 玩的日子 《 三 》 整合Redis
SpringBoot对常用的数据库支持外,对NoSQL 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结构 ...
- js数组基础
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 虚拟机下Ubuntu扩容及磁盘重新分区-Gparted
转自: https://blog.csdn.net/timsley/article/details/50742755