[Tutor] from string to variable name

Jonathon Sisson sisson.j at gmail.com
Thu Oct 5 17:02:46 CEST 2006


By "string variable that contains a name that I want to use as a
variablename" do you mean something like this:

myString = "rotationalSpeed"
rotationalSpeed = 4500

??

In Python a dictionary is an excellent solution to this problem.  The
only other way to accomplish this (to my knowledge) is in PHP (not
trying to steer you away from Python, just giving some info):

var myString = "rotationalSpeed";
$$myString = 4500;
echo $rotationalSpeed;

results in 4500.  This is called "variable variables" in PHP and it can
get hairy if done in a sloppy manner.

I'm going to make the same recommendation that Luke did.  Dictionaries
are powerful structures.  I recently wrote a Python script to parse an
English dictionary file and build Markov models out of the words
contained in the file (no, it wasn't for school, or work, or
anything...I was just really, really bored).  Rather than declaring an
int to hold the frequency information for every letter, digram, and
trigram possible (a total of 18,278 declarations), I used the letter,
digram, or trigram as a key into a dictionary.  Now I can do simple
lookups by individual letters, digrams, or trigrams and see the
frequency information without having to reference thousands of
variables, and as an added side effect, only the letters, digrams, and
trigrams that actually occur require storage.

Jonathon


Luke Paireepinart wrote:
> frank h. wrote:
>> hello, i have a string variable that  contains a name that I want to 
>> use as a variablename
>> putting aside questions of why I would like to do that - i this 
>> possible at all?
>>
>> so I want to assign a value to a variable whos name is available only 
>> as a string to me.
>> that variable does not exist yet in the local namespace.
>>
>> from: t = "myvar"
>> to: myvar = 3
>>
>> is this possible? something like setattr?
>> thanks for any insight you might have
> I think the point of dictionaries is to get this same basic 
> functionality without polluting the namespaces.
> You won't let us ask you 'why' you want to do this,
> but I'll ask you: Why don't you want to use a dictionary?
> Do you want to know if it's _Possible_ just so you'll know,
> or do you actually want to use this for something?
> If you just want to know if it's possible, I believe it is.
> But consider:
> if you don't know the variable name until runtime,
> how are you going to refer to the variable later in your code?
> It would be, insofar as I can tell, useless to do this.
>> -frank
> -Luke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list