开发者

Create variables from dictionary? [duplicate]

This question already has answers here: How do I create variable variables? (1开发者_JAVA百科7 answers) Closed 1 year ago.

Is something like the following possible in Python?

>>> vars = {'a': 5}
>>> makevars(vars)
>>> print a
5

So, makevars converts the dictionary into variables. (What is this called in general?)


It's possible, sometimes, but it's generally a very bad idea. In spite of their name, variables themselves should not be variable. They're part of your code, part of its logic. Trying to 'replace' local variables this way makes code inefficient (since Python has to drop some of its optimizations), buggy (since it can accidentally replace something you didn't expect), very hard to debug (since you can't see what's going on) and plain unreadable. Having 'dynamic values' is what dicts and lists and other containers are for.


I think this works:

locals().update(vars)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜