Most people will probably say this is a bad idea. I want to use the content of a string as the name of a variable. I want to accomplish the dreaded:
s = 'x'
x = 1
where the variable name x comes (somehow?) from the string s.
To answer the "why?", say I have a global default value for x that I want the option of overriding in a function. But:
x = 0
def f(**kw):
print x
f(x=1)
prints 0 not 1. If I could use the strings in kw.keys() to reassign x (or any other globally set variables) then I'd be happy.
I realize that this works for reassigning x in f:
x = 0
def f(x=x):
print x
f(x=1)
But I want to do this for cases where there are MANY variables in my namespace that I might at some point want to override without rewriting every function definition in my module.
解决方案
Check out exec
>>> print x
Traceback (most recent call last):
File "", line 1, in
NameError: name 'x' is not defined
>>> s = 'x'
>>> exec(s + " = 1")
>>> print x
1
After a little experimentation, this also seems to work:
>>> print x
Traceback (most recent call last):
File "", line 1, in
NameError: name 'x' is not defined
>>> s = 'x'
>>> globals()[s] = 1
>>> print x
1