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

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 11 Jun 2002 01:10:04 -0700 (PDT)


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.