I have read Cannot change global variables in a function through an exec() statement?, but this is not my case.
When i run test()
, it raises exception UnboundLocalError: local variable 'var' referenced before assignment
, it looks like exec('global var', globals())
doesn't work.
var = 1
def test():
exec('global var', globals()) # The effect it achieves is different from `global var`, why?
var += 1
test()
print(var)
But if i change the function to the following, it worked:
def test():
exec('global var', globals())
exec('var += 1', globals())
I don't know why, can anyone explain?