views:

95

answers:

2

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?)

A: 

I think this works:

locals().update(vars)
DiggyF
Usually (meaning inside functions), locals() gives you a copy of the local namespace. Modifying it doesn't modify the local namespace.
Thomas Wouters
"The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter." http://docs.python.org/library/functions.html#locals
Skilldrick
But with `globals()` should work, shouldn't it?
Ricardo
`globals()` would "work", but only for globals, and modifying it is a big sign that something's wrong with your logic.
Thomas Wouters
+5  A: 

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.

Thomas Wouters
"It's possible, sometimes" -> So, how? :)
fuenfundachtzig
As in the discussion of the other answers, you can do it to `globals()`, which is a really bad idea, and you can sort-of-with-limitations do it with `exec`, which is a phenomenally terrible idea. Seriously, ‘variable variables’ are a huge mistake, even more problematic in Python than in other languages. There is almost never a good use for them. I've done all sorts of foul introspection and code-generation hacks in Python before, and I've never needed them. You've got dicts and you can make a dict work with object-style access; you shouldn't need variable-variables.
bobince