在Python中使用eval或exec设置全局变量

1 投票
2 回答
1001 浏览
提问于 2025-04-18 10:38

我先说一下,我完全同意你应该在变量名中避免使用数据,不过我们假装你想要一个这样的函数:

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.

2 个回答

0

这个看起来有效:

# 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()
3

这一定要用exec/eval的技巧吗?

def setglobal(s, x):
    globals()[s] = x

撰写回答