python:关于 exec 语句的奇怪行为

发布于 2024-12-16 11:43:09 字数 1143 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逐鹿 2024-12-23 11:43:09

我就把它留在这里:

>>> code = "a_bad_idea.func_globals['__builtins__'].open.__doc__"
>>> print eval(code, {}, {'a_bad_idea': lambda: None})
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the
preferred way to open a file.  See file.__doc__ for further information.

I will just leave it here:

>>> code = "a_bad_idea.func_globals['__builtins__'].open.__doc__"
>>> print eval(code, {}, {'a_bad_idea': lambda: None})
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object.  This is the
preferred way to open a file.  See file.__doc__ for further information.
树深时见影 2024-12-23 11:43:09

我认为脚本应该作为闭包执行,但事实并非如此。

当脚本被执行时,它似乎进行了一个新的上下文。

根据 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文