[Tutor] Assigning variables with names set by other variables

Wayne Werner waynejwerner at gmail.com
Fri Nov 4 22:38:49 CET 2011


On Fri, Nov 4, 2011 at 4:21 PM, Max S. <maxskywalker1 at gmail.com> 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.)
>

There are a few ways to do what you want. The most dangerous (you should
never use this unless you are 100% absolutely, totally for certain that the
input will be safe. Which means you should probably not use it) method is
by using exec(), which does what it sounds like: it executes whatever is
passed to it in a string:

>>> statement = input("Variable name: ")
Variable name: var
>>> exec(statement + "=4")
>>> var
4

The (hopefully) obvious danger here is that someone could type anything
into this statement:

>>> statement = input("Variable name: ")
Variable name: import sys; sys.exit(1); x
>>> exec(statement + " =4")

and now you're at your prompt. If the user wanted to do something more
malicious there are commands like shutil.rmtree that could do *much* more
damage.

A much safer way is to use a dictionary:

>>> safety = {}
>>> safety[input("Variable Name: ")] = 4
Variable Name: my_var
>>> safety["my_var"]
4

It requires a little more typing, but it also has the advantage of
accepting perfectly arbitrary strings.

There may be some other ways to do what you want, but hopefully that should
get you started.
HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111104/cb760f2f/attachment.html>


More information about the Tutor mailing list