This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: exec() ignores scope.
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.8, Python 3.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: exec docs should note that the no argument form in a local scope is really the two argument form
View: 24800
Assigned To: Nosy List: Keepun, eryksun, mark.dickinson
Priority: normal Keywords:

Created on 2021-03-09 15:42 by Keepun, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg388366 - (view) Author: Keepun (Keepun) Date: 2021-03-09 15:42
exec() ignores scope.

Code:
--------------------------
class ExecTest:
    def public(self):
        h=None
        exec("h='It is public'")
        print(h)
        self._private()
    def _private(self):
        h=None
        exec("h='It is private'", globals(), locals())
        print(h)

h = None
exec("h='It is global'")
print(h)

e=ExecTest()
e.public()

Result
--------------------------
It is global
None
None

--------------------------
Python 3.7.10 (default, Feb 26 2021, 13:06:18) [MSC v.1916 64 bit (AMD64)]
and
Python 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0]
msg388370 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2021-03-09 16:41
exec(obj, globals(), locals()) is the same as exec(obj). Also, locals in a function scope are optimized, so the locals() dict is a snapshot. Modifying the snapshot dict doesn't modify the optimized local variables. At most I think this issue is a duplicate of bpo-24800, to clarify the implicit local scope and behavior.
msg388425 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2021-03-10 11:09
> At most I think this issue is a duplicate of bpo-24800

Agreed; closing here.
History
Date User Action Args
2022-04-11 14:59:42adminsetgithub: 87614
2021-03-10 11:09:55mark.dickinsonsetstatus: open -> closed

superseder: exec docs should note that the no argument form in a local scope is really the two argument form

nosy: + mark.dickinson
messages: + msg388425
resolution: duplicate
stage: resolved
2021-03-09 16:41:50eryksunsetnosy: + eryksun
messages: + msg388370
2021-03-09 15:42:58Keepuncreate