usustarr usustarr - 4 months ago 24
Python Question

Elegant way of loading series of objects into a list

I have a need to iterate over bunch of objects(30+ Objects are for 30+ buttons). Therefore I have a list looks like this,

myObjList = [my.obj.obj1, my.obj.obj2, my.obj.obj3, ....... ]

What would be the most elegant way to load a list with these objects?


Since you're looking for flexible dot access, you're probably best off with getattr in a list comprehension:

myObjList = [getattr(my.obj, 'obj'+str(i)) for i in range(n)]

where n is the number of obj<i> you need to get from my.obj.