简体   繁体   中英

Assigning a variable to a variable via raw_input?

I am trying to get input from a user into a variable but instead of a string, float or integer I want it to assign a different variable which is already defined. Pseudo-ish example:

xy = 23
a = raw_input("Enter a variable") xy
print (a)
23

Yes, this could be controlled with an if variable but for many variables this is not very practical I believe? I have no problem typing it just wondering wouldn't it be bad practice?

You can use globals() to get a dict with all the variables in the global namespace, or locals() for the local namespace:

>>> xy = 23
>>> a = globals()[raw_input("Enter a variable ")]
Enter a variable xy
>>> print (a)
23
>>> globals()
{'a': 23, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None
, 'xy': 23, '__name__': '__main__', '__doc__': None}

More info about them. At top-level, both will return the same dict, but the difference can be seen when used inside a function:

>>> def foo(x):
...   print globals()
...   print locals()
...
>>> foo(10)
{'a': 23, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None
, 'xy': 23, '__name__': '__main__', 'foo': <function foo at 0x00BC5FB0>, '__doc_
_': None}
{'x': 10}

Note that this technique does not involve eval in any way, so if an user attempts to enter a malicious input it will just raise a keyError . However, depending on what you plan to do with the variable, there might be some security risks nonetheless (in this sense, using locals() is safer, since you can control over the precise set of variables that can be accessed this way).

Are you looking for something like this?

xy = 23
a = eval(raw_input("Enter a variable"))
print (a)

The task of adding a check in case the user enters an unkown variable is left to the reader...

Also beware of the potential security problems of this approach. A more secure way would be to restrict the evaluation scope by defining specific dict s that eval should be using. Read more in help(eval) .

Just hold your var's in a dict, it's also probably the safest:

In [52]: d={'x':1,'y':2,'z':3}

In [53]: a=d.get(raw_input('enter var'),None)

Example:

In [57]: a=d.get(raw_input('enter var: '),None)

enter var: y

In [58]: print a
2

In [59]: a=d.get(raw_input('enter var: '),None) # You can specify a default value

enter var: Foo

In [60]: print a
None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM