String as a Variable?

Alex Martelli aleaxit at yahoo.com
Fri Feb 2 11:05:39 EST 2001


<binnc at my-deja.com> wrote in message news:95eih7$si$1 at nnrp1.deja.com...
> Another newbie question...
>
> Is there a way to have a string represent a variable.

Yes, there are quite a few.  It's an *exceedingly* rare
occurrence that using any of those ways is actually the
best approach to anything, though; you would most likely
be best advised to refactor your code to work otherwise.


> For eaxample, I have a the following:
>
> <snip>
>
> serial_number = '3'
> print 'ip_address_serial_' + serial_number
> ip_address_serial_3
>
> Now I want to use the string ip_address_serial_3 to pull
> the value assigned to the variable of the same name.

The built-in function vars() returns a mapping that
represents the variable-to-value correspondence at
this time.  Indexing that mapping with a string will
return the value currently corresponding to the
variable whose name is that string -- if no such
variable exists, of course, a KeyError will be raised.

I.e.,

    print vars()['ip_address_serial_' + serial_number]

will print the value you require.

But it's a bad ideas to use variables in this way.

Why not have ip_addresses be a dictionary, and
index it with '3' directly?  This is much more
direct, explicit, simple, and well-performing, than
hiding the 'pieces' of a mapping as part of the
vars-dictionary -- which is what you're doing when
you use variables (rather than dictionary entries)
to refer to values, but then want to access them by
string-index.

Further, vars() and friends do not, in general, let
you RE-BIND variables to new values -- only access
the value a variable is currently bound to.

You can bypass these issues with the exec statement
(and, as you're at it, you might use the eval
function to fetch your variables -- it's overkill,
though).  But, MUCH better, you can bypass them by
using a dictionary when a dictionary is what you
really want.


Alex






More information about the Python-list mailing list