简体   繁体   中英

python exec command does not pick up globals with custom scope?

Consider the following code:

code = '''
s = "hi"

def x():
    print(s)

x()
'''

# does not work
exec(code, {}, {})

# works
exec(code, globals(), locals()) # works

When we use exec with custom globals and locals it runs into an error where it does not recognize s

NameError: name 's' is not defined

When we use the default globals and locals though exec(code, globals(), locals()) , everything is fine.

How can I have exec detect globals (within the code to be executed) with custom scope ie exec(code, {}, {}) ?

s is obviously not in the scope of the function x(). You cannot print it unless you can access it from inside the function, which the second allows to do by declaring that there are globals to be considered.

If you insist on using exec(code, {}, {}) you can declare s as a global variable:

def x():
    global s
    print(s)

Now both calls will work

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