[Tutor] Assigning variables with names set by other variables
Peter Otten
__peter__ at web.de
Fri Nov 4 22:43:00 CET 2011
Max S. wrote:
> Is it possible to create a variable with a string held by another variable
> in Python? For example,
>
>>>> var_name = input("Variable name: ")
> (input: 'var')
>>>> var_name = 4
>>>> print(var)
> (output: 4)
>
> (Yeah, I know that if this gets typed into Python, it won't work. It just
> pseudocode.)
>
> I'm on a Windows Vista with Python 3.2.2. Thanks.
The direct translation into python uses exec()
>>> name = input("variable name: ")
variable name: var
>>> exec(name + " = 4")
>>> var
4
However, exec() can execute arbitrary code, and if a malicious user enters
import shutil; shutil.rmtree("/path/to/your/data"); x
as the "variable name" you may be in trouble. Therefore experienced users
normally use a dictionary instead:
>>> namespace = {}
>>> name = input("variable name: ")
variable name: var
>>> namespace[name] = 4
>>> namespace[name]
4
It may look less convenient at first sight, but can save you a lot of
trouble later on.
More information about the Tutor
mailing list