Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

DOCS: Suggest always calling exec with a globals argument and no locals argument #119235

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

Merged
merged 2 commits into from
May 20, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
DOCS: Suggest always calling exec with a globals argument and no loca…
…ls argument

Many users think they want a locals argument for various reasons but they do not
understand that it makes code be treated as a class definition. They do not want
their code treated as a class definition and get surprised. The reason not
to pass locals specifically is that the following code raises a `NameError`:

```py
exec("""
def f():
    print("hi")

f()

def g():
    f()
g()
""", {}, {})

```
The reason not to leave out globals is as follows:
```py
def t():
    exec("""
def f():
    print("hi")

f()

def g():
    f()
g()
    """)
```
  • Loading branch information
hoodmane committed May 20, 2024
commit 0f09e03034f7986eaf7eb20c2b712cc85768b4ab
10 changes: 7 additions & 3 deletions 10 Doc/library/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,13 @@ are always available. They are listed here in alphabetical order.
will be used for both the global and the local variables. If *globals* and
*locals* are given, they are used for the global and local variables,
respectively. If provided, *locals* can be any mapping object. Remember
that at the module level, globals and locals are the same dictionary. If exec
gets two separate objects as *globals* and *locals*, the code will be
executed as if it were embedded in a class definition.
that at the module level, globals and locals are the same dictionary.

.. note::

You probably should always pass a globals argument and never a locals
argument. If exec gets two separate objects as *globals* and *locals*, the
code will be executed as if it were embedded in a class definition.

If the *globals* dictionary does not contain a value for the key
``__builtins__``, a reference to the dictionary of the built-in module
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.