pyscripter-er icon indicating copy to clipboard operation
pyscripter-er copied to clipboard

fix: Don't shaddow locals when running exec

Open tomdottom opened this issue 3 years ago • 0 comments

When you pass the locals arg to exec you overwrite/shaddow the locals compiled into the code object.

This results in NameErrors like:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    exec(compiled_code, {}, {})
  File "<script>", line 8, in <module>
  File "<script>", line 6, in bar
NameError: global name 'foo' is not defined

From the following simple example:

code_string = """
def foo():
    return "foo"

def bar():
    print foo()

bar()
"""
globals_, locals_ = {}, {}

exec(code_string, globals_, locals_)

The code example works when run with:

exec(code_string, globals_)

tomdottom avatar Jan 12 '22 15:01 tomdottom