1 描述

eval()  函数用来执行一个字符串表达式,并返回表达式的值

2 语法

原文

eval(expression[, globals=None[, locals=None]])

expression(sourse) -- 字符串表达式。也即,再写该表达式时不能忘记引号“ ”

    =语句字符串

globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。

    = 全局变量,若有,必须是字典。

locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

    =局部变量,若有,必须是字典,若无,则等同于globals

3 返回值

返回表达式expression执行结果

4 练习

4.1 执行动态语句

>>> eval("1+2")
3
print(eval("1+2")) #3

4.2 globals 与locals 省略

官方示例

>>> x=1
>>> eval("x+1")
2

也可以时多个参数

x = 1
y = 2
a = eval("x+y")

print("a =",a)

运行:

a = 3

注意:


a = eval("x+y")

等价于

a = eval("x+y",{"x":1,"y":2},{"x":1,"y":2})

4.2 globals和locals省略问题

x = 100
y = 200

ls = {"x":1,"y":2}

c = eval("x+y",ls)

print("c =",c)
print("x = %d,y = %d"%(x,y))

运行

c = 3
x = 100,y = 200

 
x = 100
y = 200

ls = {"x":1,"y":2}
gs = {"x":3,"y":4}

a = eval("x+y",ls,gs)
print("a =",a)    #a = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200

print("-------------------------------")

b = eval("x+y",ls)
print("b =",b)    #b = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200

print("-------------------------------")

c = eval("x+y",ls,None)
print("c =",c)    #c = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))     #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200

print("-------------------------------")

d = eval("x+y",None,gs)
print("d =",d)    d = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200

运行

a = 7
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-------------------------------
b = 3
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-------------------------------
c = 3
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200
-------------------------------
d = 7
ls[x] = 1,ls[y] = 2
gs[x] = 3,gs[y] = 4
x = 100, y = 200

4.4关于变量绑定时的报错

尽管 x 已经定义,但是不是全局变量

>>> {"x":1}
{'x': 1}
>>> eval("x+1")   #   在全部变量中没有定义
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> a = {"x":1}
>>> eval("a['x']+1")  # 这里一定要注意不能内外均是双引号,这样会报错
2
>>> a = {"x":1}
>>> eval("x+1",a)  #在a中有x的定义,可以执行
2

5 原技术文档

eval(expressionglobals=Nonelocals=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 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.

6 参考

https://www.cnblogs.com/sesshoumaru/p/5995712.html

6  参考

最新文章

  1. 本地hosts临时域名访问
  2. linux常见目录的作用
  3. php 基本符号
  4. [C++]VisualAssistX中文注释提示错误 解决办法
  5. java.lang.ClassCastException: com.sun.proxy.$Proxy8 cannot be cast to com.bjsxt.service.UserServiceImpl01_AOP.
  6. dede list列表页和文章页分别使用if else
  7. hdu1045 Fire Net---二进制枚举子集
  8. 检测Tensorflow可用设备(比如:显卡)
  9. 多个窗口开启后,切换到指定title的窗口
  10. 为什么我们要使用HTTP Strict Transport Security?
  11. vue 里面引入高德地图
  12. hdu-4819-线段树套线段树
  13. js组件的写法
  14. 使用html+css+js实现计算器
  15. leetcode python找不同
  16. Codeforces 1108F (MST Unification) (树上倍增 or 改进 kruksal)
  17. RobotFramework自动化3-搜索案例【转载】
  18. H - Funny Car Racing
  19. IX Samara Regional Intercollegiate Programming Contest F 三分
  20. redis实现分布式锁——核心 setx+pipe watch监控key变化-事务

热门文章

  1. 3D几何图形的生成算法
  2. LZO 使用和介绍
  3. SQL基础(二):SQL命令
  4. C++类模板的三种特化
  5. Jenkins——应用篇——插件使用——Publish over SSH
  6. CloudStack无法添加模板和iso
  7. (转)U3D DrawCall优化手记
  8. DockPanel 类
  9. C#.NET常见问题(FAQ)-程序不包含适合于入口点的静态“Main”方法怎么办
  10. Java开发中所遇问题积累