storing variable names in a list before they are used?

Ant antroy at gmail.com
Fri Sep 29 16:32:52 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
...
> 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()

A better way of doing it may be to use a dictionary thus:

name_map = {"First Name": None, "Last Name": None}

and then assign the value:

name_map["First Name"] = widget.get_text()

Or alternatively if you were adamant you wanted your original format:

firstname = [None]
lastname = [None]

 [(firstname, 'First Name:'), (lastname, 'Last Name:')]

firstname[0] = widget.get_text()

But that's a bit of a hack.

The problem you are having here is a conceptual one: When you put a
variable name in a list or tuple, it isn't the *name* that's stored but
the actual value. I would think about using the dictionary version
above, or if things are getting more complicated, then create a class
to produce objects that contain the structure you want:

class FormField(object):
    def __init__(self, name, text=None):
        self.name = name
        self.text = text

firstname = FormField("First Name", "Default Text")
lastname = FormField("Last Name")

fields = [firstname, lastname]

lastname.text = widget.get_text()

The same of course could be accompished using pairs or dictionaries
(e.g. firstname = {"name": "First Name", "text": "Default Text"};
lastname = {"name": "Last Name"} ), but I think that the class based
version self documents itself a bit better.




More information about the Python-list mailing list