Using an interable in place of *args?
nav+posts at bandersnatch.org.invalid
Fri Nov 21 17:49:45 CET 2003
I'm building a wrapper class for the struct module to help me handle
network data. The tin can on the other end of the string is probably a
C program that does pointer casts into C structures. I'd like to build
a helper class to pack and unpack these datagrams. It will rely on the
struct module for packing and unpacking the data.
I've done the unpacking method quite easily. Another one of those
tasks that makes you feel like programming is a fun and rewarding
pastime, thanks to Python. Problems show up when I try to pack the
data back into a binary string, because struct.pack's arugments are
(format, *args). The problem is, I don't know what *args will be when
I declare the class, only when an object is instantiated.
Is there a general method for calling a function that expects *args
with an iterable instead (tuple or, even better, a list)? I can see
how I could do something funky with exec, but I'd like to avoid that
I considered hacking structmodule.c, but that would involve climbing a
certain learning curve, and I would much rather not depend on
non-standard behavior in the standard library.
Thanks for any pointers people might have...
p.s. Here's the module as it stands (minus some front matter):
def __init__(self, structure, hasblob = False):
self.format = ''.join([ y for x, y in structure ])
self.fields = [ x for x, y in structure ]
self.hasblob = hasblob
for v in self.fields:
self.__dict__[v] = None
self.blob = None
self.structsize = struct.calcsize(self.format)
def unpack(self, dat):
elements = struct.unpack(self.format, dat[:self.structsize])
for k, v in zip(self.fields, elements):
self.__dict__[k] = v
self.blob = dat[self.structsize:]
# need some way to call struct.pack with a list/tuple of values
# built with [ self.__dict__[v] for v in self.fields ]
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
More information about the Python-list