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(), locals() and local variable access
Type: behavior Stage:
Components: Interpreter Core Versions: Python 3.1
process
Status: closed Resolution: works for me
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, splay657
Priority: normal Keywords:

Created on 2009-09-08 07:22 by splay657, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg92409 - (view) Author: john zeng (splay657) Date: 2009-09-08 07:22
Can you help me understand why variable `u' is not accessible after 
exec()? Is this sort of a late binding issue?

def test(v1):
    print(v1)
    print("Before exec(): " + str(locals()))
    exec(v1)
    print("After  exec(): " + str(locals()))
#   This fails:
#    print(u)
#   This is workaround:
    en = locals()['u']
    print(en)

v1="u=4"
test(v1)
msg92410 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) * (Python committer) Date: 2009-09-08 08:20
When the parser analyzes the test() function, it determines that 'u' in
"print(u)" is a global variable. But exec modifies the local namespace...

You could add a "u=None" near the start of the function, or better,
always use a namespace for the exec statement:

d = {}
exec v1 in d
en = d['u']
History
Date User Action Args
2022-04-11 14:56:52adminsetgithub: 51111
2009-09-08 08:20:29amaury.forgeotdarcsetstatus: open -> closed

nosy: + amaury.forgeotdarc
messages: + msg92410

resolution: works for me
2009-09-08 07:22:06splay657create