python:关于 exec 语句的奇怪行为
exec 语句:
exec code [ in globals[, locals]]
当我在 python 中执行以下代码时,结果确实让我困惑。一些变量被设置到全局变量中,一些变量被设置到局部变量中。
s = """
# test var define
int_v1 = 1
list_v1 = [1, 2, 3]
dict_v1 = {1: 'hello', 2:'world', 3:'!'}
# test built-in function
list_v2 = [float(x) for x in list_v1]
len_list_v1 = len(list_v1)
# test function define
def func():
global g_var, list_v1, dict_v1
print 'access var in globals:'
print g_var
print 'access var in locals:'
for x in list_v1:
print dict_v1[x]
"""
g = {'__builtins__': __builtins__, 'g_var': 'global'}
l = {}
exec s in g, l
print 'globals:', g
print 'locals:', l
exec 'func()' in g, l
python2.6.5 中的结果:
globals: {'__builtins__': <module '__builtin__' (built-in)>, 'dict_v1': {1: 'hello', 2: 'world', 3: '!'}, 'g_var': 'global', 'list_v1': [1, 2, 3]}
locals: {'int_v1': 1, 'func': <function func at 0x00ACA270>, 'x': 3, 'len_list_v1': 3, 'list_v2': [1.0, 2.0, 3.0]}
access var in globals:
global
access var in locals:
hello
world
!
如果我想将所有变量和函数设置到局部变量中,并保留访问全局变量的权限。怎么办?
exec statement:
exec code [ in globals[, locals]]
When I execute the following code in python, the result really confused me. Some of the variables were setup into the globals, some were setup into the locals.
s = """
# test var define
int_v1 = 1
list_v1 = [1, 2, 3]
dict_v1 = {1: 'hello', 2:'world', 3:'!'}
# test built-in function
list_v2 = [float(x) for x in list_v1]
len_list_v1 = len(list_v1)
# test function define
def func():
global g_var, list_v1, dict_v1
print 'access var in globals:'
print g_var
print 'access var in locals:'
for x in list_v1:
print dict_v1[x]
"""
g = {'__builtins__': __builtins__, 'g_var': 'global'}
l = {}
exec s in g, l
print 'globals:', g
print 'locals:', l
exec 'func()' in g, l
the result in python2.6.5:
globals: {'__builtins__': <module '__builtin__' (built-in)>, 'dict_v1': {1: 'hello', 2: 'world', 3: '!'}, 'g_var': 'global', 'list_v1': [1, 2, 3]}
locals: {'int_v1': 1, 'func': <function func at 0x00ACA270>, 'x': 3, 'len_list_v1': 3, 'list_v2': [1.0, 2.0, 3.0]}
access var in globals:
global
access var in locals:
hello
world
!
And if I want to setup all variables and functions into the locals, and keep the rights of accessing the globals. How to do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我就把它留在这里:
I will just leave it here:
我认为脚本应该作为闭包执行,但事实并非如此。
当脚本被执行时,它似乎进行了一个新的上下文。
根据 LEGB 规则,封闭范围没有任何内容,因此 script 中的函数永远无法访问 exec 语句中的本地字典。
I think the script should execute as a closure, but it does not.
It seems to conduct a new context, while the script was executed.
According to the LEGB Rule, the enclosuring scope was nothing, so that the function in script could never access to the locals dict in exec statement.