Create variables from dictionary? [duplicate]
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)
精彩评论