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, {}, {})
?