简体   繁体   中英

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():
    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?

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:

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

and then trying to use it in a different module:

# bar.py
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.

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