简体   繁体   中英

python: strange behavior about exec statement

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM