Is it possible to “dynamically” create local variables in Python? [duplicate]

跟風遠走 提交于 2019-11-28 12:11:26

If you really want to do this, you could use exec:

print 'iWantAVariableWithThisName' in locals()
junkVar = 'iWantAVariableWithThisName'
exec(junkVar + " = 1")
print 'iWantAVariableWithThisName' in locals()

Of course, anyone will tell you how dangerous and hackish using exec is, but then so will be any implementation of this "trickery."

You can play games and update locals() manually, which will sometimes work, but you shouldn't. It's specifically warned against in the docs. If I had to do this, I'd probably use exec:

>>> 'iWantAVariableWithThisName' in locals()
False
>>> junkVar = 'iWantAVariableWithThisName'
>>> exec(junkVar + '= None')
>>> 'iWantAVariableWithThisName' in locals()
True
>>> print iWantAVariableWithThisName
None

But ninety-three times out of one hundred you really want to use a dictionary instead.

No need to use exec, but locals()[string], or vars() or globals() also work.

test1="Inited"

if not "test1" in locals(): locals()["test1"] = "Changed"
if not "test1" in locals(): locals()["test2"] = "Changed"

print " test1= ",test1,"\n test2=",test2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!