Dynamically created objects

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Fri Dec 28 02:44:16 EST 2007


On Fri, 28 Dec 2007 08:14:43 +0100, Michael Bernhard Arp Sørensen wrote:

> Hi there.
> 
> I need to create objects on the fly in my program. The names of the
> objects must be unique, obviously, and I need to put them in a list for
> later use.

Why do you think they need names? If you have them in a list, just refer 
to them by the list and index. Or a dict and a key.

E.g. instead of this:


# this doesn't work
for i in range(10):
    "foo" + i = "some data here"  # variables like foo0, foo1 ...
process(foo0, foo1, foo2)



do this:

foo = []
for i in range(10):
    foo.append("some data here")
process(foo[0], foo[1], foo[2])




> How do i set the name of an object if the name is stored in another
> variable?


If you really need to do this, and I doubt that you do, here's one way:


>>> bird
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bird' is not defined
>>> globals()["bird"] = "a parrot with beautiful plumage"
>>> bird
'a parrot with beautiful plumage'


If you're tempted to try the same trick with locals(), don't bother -- it 
won't reliably work.

If you are absolutely sure that the data is safe (i.e. you control it, 
not random users via a web form) you can also use exec.



-- 
Steven



More information about the Python-list mailing list