jordanwh jordanwh - 2 years ago 92
Python Question

Using globals in Python exec

I'm trying to create a custom python interpreter type application. I'm using exec statement (in Python 2.7.6) to execute given code but globals aren't working quite as expected. Could someone explain why this does not work:

def 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, do the globals passed to exec not carry over to called functions?

Answer Source

The x inside the function is picked up from the globals of the namespace where the function is defined. However, you're calling it in a different namespace. This isn't too different from having multiple modules:

def print_x():

and then trying to use it in a different module:

from foo import print_x

x = 10
print_x()  # NameError

Ultimately, g is the globals in the execution context of exec. After it calls the print_x function (which was defined in a different global context), you can't expect print_x to know anything about the globals in exec's execution context -- print_x only knows the globals in it's module's context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download