Per the docs, the exec
statement takes two optional expressions, defaulting to globals()
and locals()
, and always performs changes (if any) in the locals()
one.
So, just be more explicit/specific/precise...:
>>> def myfunc():
... exec('myvar="boooh!"', globals())
...
>>> myfunc()
>>> myvar
'boooh!'
...and you'll be able to clobber global variables to your heart's contents.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…