[Tutor] creating objects in a loop

Brad Reisfeld brad.reisfeld@colostate.edu
Tue, 2 Apr 2002 11:33:37 -0700


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.

-Brad