[Tutor] Creating an Identifier or Object Name from a String?

Dan Shafer pydan@danshafer.com
Tue, 11 Jun 2002 15:13:11 -0700


Thanks, Danny. With your code as a clue for a starting point, I got this 
working just fine for list and dictionaries.

Appreciate it.

At 01:10 AM 6/11/2002 -0700, Danny Yoo wrote:


>On Tue, 11 Jun 2002, Dan Shafer wrote:
>
> > I have a need to refer to a number of objects which have been named
> > field1, field2, field3, etc. I want to set a property in each object in
> > a loop.
>
>Instead of having them as separate variables, is it possible to keep them
>grouped together in a list or dictionary?  That way, it's easier to work
>with them as a group, without the complexities of eval().
>
>
> > I thought this should work:
> >
> >    for ct in range(1,4):
> >      objToUpdate = "field" + str(ct)
> >      objToChange = eval(objToUpdate) # seems like it should produce
> > "field1" first time through the loop, etc.
> >      objToChange.text = inputList[ct] #inputList is generated prior to
> > entering the loop and is a list of string values
>
>
>So since your inputList is already a list, that may be a good hint that
>symmetry will help.  *grin* Try something like:
>
>###
>objects = [field1, field2, field3]  ### Add as many objects as you
>                                     ### have
>for i in range(len(objects)):
>     objects[i].text = inputlist[i]
>###
>
>
>But I didn't see anything obviously wrong with your initial approach.
>One suggestion would be to check the value of field1, field2, field3,
>right before the loop.  Also, if you can show us the literal error
>message, that may give more clues as to why it's doing weird things.

Dan Shafer, Chief Scribe and Tablet Keeper
PythonCard Open Source Project
http://pythoncard.sourceforge.net