开发者

Create a new variable as named from input in Python?

开发者 https://www.devze.com 2023-01-21 02:35 出处:网络
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

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消