I am trying to declare python variables using the function exec from within a function. For example:
def func():
varnames = ['x', 'y', 'z']
vals = [5,5,'abc']
exec(varnames[0] + '=vals[0]')
print(x)
func()
results in the error:
NameError: global name 'x' is not defined
However, it is indeed the case that 'x' is in locals()
def func():
varnames = ['x', 'y', 'z']
vals = [5,5,'abc']
exec(varnames[0] + '=vals[0]')
print(locals())
func()
results in:
{'vals': [5, 5, 'abc'], 'x': 5, 'varnames': ['x', 'y', 'z']}
showing that x is present in the local namespace. Any idea why this is happening or how I can get around it?