Is there a more elegant way to do this?

Peter Hansen peter at engcorp.com
Mon Jun 28 15:20:12 CEST 2004


Kamilche wrote:

> Is there a more elegant way of doing this?
> I would like to have the arguments to pack
> automatically taken from lst.
>
>     def pack(self):
>         lst = ['id', 'parent', 'number', 'x', 'y', 'z', 'red', \
>                    'green', 'blue', 'size', 'rotate', 'translucency']
>         return struct.pack('<IIIiiiBBBHHH', \
>                            self.id, self.parent, self.number,   \
>                            self.x, self.y, self.z,  \
>                            self.red, self.green, self.blue, \
>                            self.size, self.rotate, self.translucency)

The following is perhaps the most easily maintainable
of the responses *if* you expect things to change at
all.  If the whole thing is very stable, the explicit
approach, as Peter Otten says, might be preferred.

def pack(self):
     args = ('Iid Iparent Inumber ix iy iz Bred Bgreen Bblue '
         'Hsize Hrotate Htranslucency')
     lst = zip(*[(x[0],x[1:]) for x in s.split()])
     return struct.pack('<' + ''.join(lst[0]),
         *[getattr(self, n) for n in lst[1]])

It's also easily the most inscrutable of the responses... but
if you have to do this sort of thing in various places in your
code, it makes a nice utility function.

-Peter



More information about the Python-list mailing list