在Python中使用eval或exec设置全局变量
让我首先说我完全同意你应该 但让我们假设您需要这样一个函数:在Python中使用eval或exec设置全局变量,python,metaprogramming,eval,Python,Metaprogramming,Eval,让我首先说我完全同意你应该 但让我们假设您需要这样一个函数: def setglobal(s, x): # Some kind of eval or exec trick like eval(s+' = '+x) so we end up # with a global variable whose name is the string s and that has a value of x. 这似乎有效: # Take a symbol name s as a string and
def setglobal(s, x):
# Some kind of eval or exec trick like eval(s+' = '+x) so we end up
# with a global variable whose name is the string s and that has a value of x.
这似乎有效:
# Take a symbol name s as a string and a value x and eval(s+' = '+x) to set a
# global variable with name s to value x. For getglobal(s) use eval(s).
def setglobal(s, x):
exec "global "+s+"; "+s+" = "+repr(x) in globals()
这一定是执行/评估技巧吗
def setglobal(s, x):
globals()[s] = x
您还可以维护一个全局dict,在其中添加键s和值x。为了便于讨论,您对这样的函数感兴趣吗?我很不好意思说!)好的,我试着解释一下:我有一个包含几十个API参数的字典,我用它们做了一大堆计算,所以总是像
p['foo']
那样引用它们,而不仅仅是foo
,会很乏味。这听起来疯狂吗,或者我可能把事情都搞错了?