I have two blocks of python code, one works, and the other doesn't.
Working block:
env = {'user':'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
print(user)
output:
xyz
The block, which doesn't work:
def test():
env = {'user':'xyz'}
for key, value in env.items():
exec("{} = value".format(key))
print(user)
test()
output:
NameError: name 'user' is not defined
The only difference I see is that the first block is being called in the global scope.
Could you please explain?
Many thanks!
PS: With all due respect, I know, I should avoid using exec() but what if I want to.