storing variable names in a list before they are used?

Steve Holden steve at holdenweb.com
Sat Sep 30 03:35:48 EDT 2006


John Salerno wrote:
> If I want to have a list like this:
> 
> [(first_name, 'First Name:'), (last_name, 'Last Name:').....]
> 
> where the first part of each tuple is a variable name and the second 
> part is a label for the user to see, such as a form like this:
> 
> First Name: ________
> Last Name:  ________
> 
> (the variables would store whatever information is entered in the text 
> boxes to the right of each label. I'm doing it this way so I can write a 
> loop to construct my GUI components).
> 
> how would I go about putting these variable names in a list? I know I 
> can't leave them as above, but if I put them in as a string, then how do 
> I later "transform" them into an actual variable for assign, such as:
> 
> first_name = widget.get_text()
> 
> Is there some kind of idiom that does this sort of work?
> 
> Thanks.

There are ways you can do this, but the best advice is "don't". If you 
are putting names into a Python namespace that aren't known in advance 
then you also have to use similarly obscure techniques to access the 
variables, and you are running the risk that your code will collide whit 
a name of a variable already used in that namespace by your code.

What's wring with just using a dict to store the values against the 
names? Dicts and namespaces have a lot of behaviour in common.

regard
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list