python: strange behavior about exec statement

Posted by ifocus on Stack Overflow See other posts from Stack Overflow or by ifocus
Published on 2011-11-16T06:13:00Z Indexed on 2011/11/21 1:51 UTC
Read the original article Hit count: 215

Filed under:
|

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 ?

© Stack Overflow or respective owner

Related posts about python

Related posts about exec