[Tutor] creating objects in a loop

Kirby Urner urnerk@qwest.net
Tue, 02 Apr 2002 12:16:22 -0800


At 11:33 AM 4/2/2002 -0700, Brad Reisfeld wrote:
>Hi,
>I was wondering if there is an efficient way to create objects based on
>looping through members of a list or dictionary.
>
>For instance, suppose I have
>
> >>> class Pets:
>...   def __init__(self, name):
>...     self.name = name
>
> >>> petlist = [('cat','fluffy'),('dog','fido'),('gorilla','spike')]
>
>and I want to do the following:
>
> >>> cat = Pets('fluffy')
> >>> dog = Pets('fido')
> >>> gorilla = Pets('spike')
>
>Right now, I can use
>
> >>> for species,name in petlist:
>...   exec("%s = Pets('%s')" % (species, name))
>
>
>This seems to do the right thing, but the use of the 'exec' kludge seems
>really ugly and inefficient.
>
>What is the proper way to do this? My lists and/or dictionaries in my actual
>application may be quite large.
>
>Thanks.

You can use the species as a key to a dictionary,
i.e.

petsdict['gorilla'] = Pets('spike') # and...
petsdict['dog']     = Pets('fido')

In other words:

petsdict = {}
for species,name in petlist:
    petsdict[species] = Pets(name)

Filing your multiple objects in a dictionary or list
is usually better than creating a lot of top level
variables in the namespace.  If you want to temporarily
point to an object by variable name, do that inside
a function e.g.

   def changename(species,newname):
       pet = petsdict[species]
       pet.name = newname

If you insist on creating top-level variables within
the module, you can do it without exec as follows:

for species,name in petlist:
    globals()[species] = name

Kirby