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?

4
  • 2
    What are you trying to achieve? Commented Oct 25, 2010 at 14:32
  • 2
    Whatever he's trying to achieve, this approach is wrong. Use a dict (or another suitable collection - but if you want to use a string, you propably want a dict), period. Commented Oct 25, 2010 at 14:37
  • Python internals are so transparent that it's tempting to say how to do this, but much more interesting would be coming up with a case where it's a good idea. Commented Oct 25, 2010 at 14:52
  • I'm not trying to achieve anything anymore. I figured I had to do it a while back, but the same can be achieved with dict. It's more now of a 'Is that even possible?' question. Commented Oct 25, 2010 at 15:07

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.