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: Variables in locals scope fails to be printed.
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.9
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: mark.dickinson, xxm
Priority: normal Keywords:

Created on 2021-03-16 03:08 by xxm, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg388802 - (view) Author: Xinmeng Xia (xxm) Date: 2021-03-16 03:08
The following code 1 calls function 'compile' and 'exec' and execute a statement "s=1". Then we print the value of 's'.  This code can perform well on Python 3.9.2 and output the expected result. However, we pack the whole code into a function (code 2).  The execution fails. 


code 1:
===================
mstr = "s=1"
exec(compile(mstr,'','exec'))
print(s)
===================
output: 1


code2:
===================
def foo():
     mstr = "s=1"
     exec(compile(mstr,'','exec'))
     print(s)
foo()
===================
output: 
Traceback (most recent call last):
    File "/home/xxm/Desktop/apifuzz/doc/genDoc.py", line 37, in <module>
            foo()
    File "/home/xxm/Desktop/apifuzz/doc/genDoc.py", line 35, in foo
            print(s)
NameError: name 's' is not defined

By the way, we print locals().  's' exists in the local scope. It should not fail.
>>print(locals())
{'mstr': 's=1', 's': 1}
msg388825 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2021-03-16 08:43
I think this is essentially a duplicate of #24800. (Short version, the behaviour is by design, and documented, but there may be scope for clarifying or improving the documentation.)
History
Date User Action Args
2022-04-11 14:59:42adminsetgithub: 87673
2021-03-16 10:41:20mark.dickinsonsetstatus: open -> closed
superseder: exec docs should note that the no argument form in a local scope is really the two argument form
resolution: duplicate
stage: resolved
2021-03-16 08:43:48mark.dickinsonsetnosy: + mark.dickinson
messages: + msg388825
2021-03-16 03:08:01xxmcreate