Dynamically created objects

  • Thread starter Michael Bernhard Arp Sørensen
  • Start date
M

Michael Bernhard Arp Sørensen

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.

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

I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Thanks in advance.

/Tram
 
G

Gabriel Genellina

En Fri, 28 Dec 2007 04:14:43 -0300, Michael Bernhard Arp Sørensen
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.

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

I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Use a dictionary as a container.

py> ns = {}
py> name = "Joe"
py> o = object()
py> ns[name] = o
py> another = set("another")
py> ns["another"] = another
py> ns
{'Joe': <object object at 0x009D0478>,
'another': set(['a', 'e', 'h', 'o', 'n', 'r', 't'])}
 
S

Steven D'Aprano

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:

Traceback (most recent call last):
File said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top