Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

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