views:

68

answers:

1

This is something that I've been questioning for some time. How would I create a variable at runtime as named by the value of another variable. So, for example, the code would ask the user to input a string. A variable would then be created named after that string with a default value of "default". Is this even possible?

+3  A: 

It is possible, but it's certainly not advised. You can access the global namespace as a dict (it's a dict internally) and add entries to it.

If you were doing an interactive interpreter, say, for doing maths, or something. You would actually pass a dict to each eval() or exec that you could then re-use as it's local namespace.

As a quick, bad, example, don't do this at home:

g = globals() # get a reference to the globals dict
g[raw_input("Name Please")] = raw_input("Value Please")
print foo

Run that, it'll traceback unless you provide 'foo' to the first prompt.

Jerub