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.
execor various other means. But the local scope of a function is carved in stone at the time the function was compiled (all references get turned into an index into an array), there's no way to add names at runtime.exec()then use it - but I would rather keep it as dictionaryenv['user'] = ...because it can be more useful then creating variablesuser = ...