Skip to content

Commit a50f065

Browse files
[3.12] DOCS: Suggest always calling exec with a globals argument and no locals argument (GH-119235) (#119240)
DOCS: Suggest always calling exec with a globals argument and no locals argument (GH-119235) 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() """) ``` (cherry picked from commit 7e1a130) Co-authored-by: Hood Chatham <[email protected]>
1 parent 541b89e commit a50f065

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

Doc/library/functions.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -604,9 +604,13 @@ are always available. They are listed here in alphabetical order.
604604
will be used for both the global and the local variables. If *globals* and
605605
*locals* are given, they are used for the global and local variables,
606606
respectively. If provided, *locals* can be any mapping object. Remember
607-
that at the module level, globals and locals are the same dictionary. If exec
608-
gets two separate objects as *globals* and *locals*, the code will be
609-
executed as if it were embedded in a class definition.
607+
that at the module level, globals and locals are the same dictionary.
608+
609+
.. note::
610+
611+
Most users should just pass a *globals* argument and never *locals*.
612+
If exec gets two separate objects as *globals* and *locals*, the code
613+
will be executed as if it were embedded in a class definition.
610614

611615
If the *globals* dictionary does not contain a value for the key
612616
``__builtins__``, a reference to the dictionary of the built-in module

0 commit comments

Comments
 (0)