0

I'd like to create instances of classes getting their names from list values or dictionaries keys or values. Basically what I'd like to do is:

iter = ['foo', 'bar']
for a in iter:
    a = Cls()

and get foo and bar instances of Cls() class instead of having instance referenced by a updated at each loop.

Thanks in advance.

silopolis
  • 273
  • 2
  • 8

2 Answers2

7

Maybe with a dictionnary :

iter = ['foo', 'bar']
result = {}
for a in iter:
    result[a] = Cls()

And in result you'll have { 'foo' : instance_of_Cls, 'bar' : instance_of_Cls}

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • 3
    Shorter: `result = dict((name, Cls()) for name in iter)`. +1. – Fred Foo Jul 21 '11 at 08:12
  • @cedric this is what I'm using but I'd like to have foo.attr and foo.meth instead of result['foo'].attr etc. This is much readable and avoids messing with wrapping containers. Thank you anyway. – silopolis Jul 21 '11 at 08:42
  • @Silopolis : to do what you want, you'll have to modify your locals() dictionnary, and this is not a good solution... Why your variables have to be defined by strings ? – Cédric Julien Jul 21 '11 at 08:45
  • @cedric: actually, they don't "have to" as my code is running with the dict_of_objects trick but I wished I could make it clearer and had liked to be able to create series of objects which names are only known at config/runtime without the container hack... But this leads me to the question: if it had been possible, could I then easily access the list of instances ? reading this http://stackoverflow.com/questions/328851/python-printing-all-instances-of-a-class , it seems that embedding instances in a container is way easier. Thanks a lot :-) – silopolis Jul 21 '11 at 09:10
  • ... and finally, reading http://docs.python.org/library/weakref.html, IIUC, this could be even better to use `weakref.WeakValueDictionary()` in this case so that the list is dynamic and the objects can be garbage collected. – silopolis Jul 21 '11 at 09:34
-1

You could use dynamic code evaluation.

inst1 = eval("foo()")
inst2 = eval(a + "()")
inst3 = eval(a)()
ron
  • 9,262
  • 4
  • 40
  • 73
  • Maybe I misunderstood the question. – ron Jul 21 '11 at 08:09
  • My problem was getting inst1/2/3 from a list or dict. My question also applies if you'd wanted to create a series of dicts, or lists or whatever, getting their names from another container. – silopolis Jul 21 '11 at 09:31