Using global variables in Python exec

I am trying to create my own application like python interpreter. I use the exec statement (in Python 2.7.6) to execute the given code, but global variables do not work as expected. Can someone explain why this is not working:

def print_x():
    print(x)


g = {'x': 10, 'print_x': print_x}
l = {}

exec('print_x()', g, l)

The result (whether the print_x function is in g or l) is an error:

NameError: global name 'x' is not defined

So, are the global variables executed for exec not transferred to the called functions?

+4
source share
1 answer

xinside the function is selected from the namespace globals where the function is defined. However, you call it in a different namespace. This is not too different from having several modules:

# foo.py
def print_x():
    print(x)

:

# bar.py
from foo import print_x

x = 10
print_x()  # NameError

, g - exec. , print_x ( ), , print_x exec - print_x .

+3

All Articles