0

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 i.e. exec(code, {}, {})?

killajoule
  • 3,612
  • 7
  • 30
  • 36

1 Answers1

0

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

Wazaki
  • 899
  • 1
  • 8
  • 22
  • In fact, in real code, function do can implicitly access the global variable. Unless you need to change the value, you don't need to use `global s`. This answer doesn't answer the question well. The critical problem is the scope rules in `exec` is somehow different or called broken with normal ones. – Sraw Oct 20 '18 at 00:21
  • @Sraw thanks for the feedback ! that's an interesting point since I faced similar name errors in python because the variable used was defined earlier outside of the function definition. I need to look more into that – Wazaki Oct 20 '18 at 11:09