Skip to content

fix: Don't shaddow locals when running exec#1

Open
tomdottom wants to merge 1 commit intolanmaster53:masterfrom
tomdottom:fix/dont-shadow-locals
Open

fix: Don't shaddow locals when running exec#1
tomdottom wants to merge 1 commit intolanmaster53:masterfrom
tomdottom:fix/dont-shadow-locals

Conversation

@tomdottom
Copy link

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_)

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_)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant