I can create a global variable in a function:
def f():
global x
x=1
f()
print x
But can I do the same if I only have the name of that variable in f()?
def f(varname):
exec('global ' + varname)
exec(varname + '=1')
f('x')
print x
This doesn't work - "name 'x' is not defined". Don't tell me that this is a terrible style of programming - I know that. The question is if this is possible to do in Python.
Thanks for the answers, but the question of why exec didn't work remains. Is is somehow executed in a different context? Is it a part of a different module, so that it creates a global variable in a different module?