eval(expression, [globals=None{dict}, locals=None{dict}])
执行一个字符串表达式
python是用命名空间来记录变量的轨迹的,命名空间是一个dictionary,键是变量名,值是变量值
查找顺序:LEGB
local 局部 locals() Enclose 闭包 Global 全局 globals() Build-in 内置
# -*- coding: utf-8 -*- # @File : eval_demo.py # @Date : 2018-07-13 # @Author : Peng Shiyu x = 1 y = 2 ret1 = eval("x+y") print("global: %s" % ret1) # global: 3 def func(): x = 3 y = 4 ret2 = eval("x+y") print("func: %s" % ret2) # func: 7 ret3 = eval("x+y", globals()) print("func globals: %s" % ret3) # func globals: 3 print(locals()) func() print(globals()) """ {'y': 4, 'x': 3, 'ret3': 3, 'ret2': 7} {'__name__': '__main__', '__doc__': 'xxx', '__package__': None, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1007dce10>, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'demo/eval_demo.py', '__cached__': None, 'x': 1, 'y': 2, 'ret1': 3, 'func': <function func at 0x1007d46a8>} """ # locals()对象的值不能修改,globals()对象的值可以修改 def func_b(): x = 20 print("locals.x %s" % locals()["x"]) locals()["x"] = 30 # 尝试修改局部变量 print("locals.x %s" % locals()["x"]) print("globals.y %s" % globals()["y"]) globals()["y"] = 40 # 尝试修改全局变量 print("globals.y %s" % globals()["y"]) func_b() """ locals.x 20 locals.x 20 globals.y 2 globals.y 40 """
参考: