August 25th, 2004, 03:54 PM
Naming variables with a variable
The pseudocode I'd like to do is this:
varname = raw_input("Enter a string: ")
var = 5
Here, though, is what i would like it to do: instead the second variable being called "var", i would like for it to be called by the value of 'varname' (whatever the string is called). Is this even possible?
August 25th, 2004, 05:32 PM
It is possible, but not generally advisable, unless you have a really good reason. What if the name that the user entered was the same as a builtin function or variable? If the user entered 'open' and you then tried to open() a file then your program would crash and burn.
You can create global variables by adding them to the dictionary returned by the globals() function. You cannot do the same for locals() because it returns a copy of the local namespace, not the original. If you really, really must create a local variable the you could do it with an exec:
Exec-ing text that a user has entered is highly dangerous though, and should be avoided at all costs.
>>> name = 'foo'
>>> exec "%s = 5" % name
A much better alternative is to either create a dictionary to hold your names in, or create an empty class and use setattr to add members. This way you will not be polluting your program's namespace.
Dave - The Developers' Coach
>>> class Namespace:
>>> namespace = Namespace()
>>> setattr(namespace, name, 5)