Amaury Forgeot d'Arc added the comment:
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 state
New submission from john zeng :
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:
#