[Tutor] Dynamic-ish naming of variables?

Alan Gauld alan.gauld at freenet.co.uk
Mon Nov 22 11:55:23 CET 2004


> Well, here's why. ...

Nope, not yet.

> {'type':'CheckBox',
>     'name':'LiamClarkeCheck',
>     'position':(104, 71),
>     'checked':True,
>     'label':'CheckBox1',
>     },
>
> Python checks values assigned by the following -
>
> if self.components.LiamClarkeCheck.checked=True ....
>
> How do I do the name part randomly, short of having my module
re-write itself?

if self.components.checkboxes['LiamClarkCheck'].checked = True

does the same thing using a dictionary.

> Ideally it would iterate over a list, something along these
pseudo-lines -
>
> for name in nameList:
>
>      if self.components.%sCheck.checked=True % name
>      teamDict[name]=self.components.%sChoice.field % name
>

cb = self.comonents.checkBoxes  # saves typing!
for name in nameList:
    if cb[name].checked = True
    teamDict[name] = cb[name].field

> Any suggestions? Could I do something like the above and use eval /
> exec? I'm not too familiar with them.

No magic just a dictionary for the checkbox components.
Remember that Python uses dictionaries for all its variable
name handling interally so whatever python does with names
internally you can pretty much do explicitly by adding an
explicit dictionary.

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list