usustarr usustarr - 28 days ago 11
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?

Answer

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.

Comments