A class for C-like structuures in Python
Thomas Gagne
tgagne at ix.netcom.com
Tue Aug 8 23:18:46 EDT 2000
OK. So they really aren't C structures, but they're close.
Now, I've only been programming in Python for about two days, so naturally I'm
an expert.
My little how-to-learn-Python project is to build a Python interface to my
open-source middleware project, isectd. In the front of every packet over the
wire is a structure called IsdHeader. Client and worker programs sometimes
look at this structure for different reasons (mostly it's used by the
middleware daemon).
ANYWAY (it's a song about Alice) I needed to recreate the structure in Python
and found myself creating a lot of things that should be generally useful, so
I created a class called CStructure which I can use as a super for the
subclass IsdHeader.
To wit the attachments...
The file, IsdHeader.py, is an example of how a subclass may use it. Basically
it calls the super with a tuple of tuples describing the members and their
format (for the struct module). CStructure uses the tuples to build a
dictionary to hold the values until the programmer requests the structure as a
string (asBytes()).
-------------- next part --------------
import struct
class CStructure:
def __init__(self, theTuples):
self.fmt = ''
self.members = {}
self.shape = theTuples
for n,f in self.shape:
self.members[n] = None
self.fmt = self.fmt + f
def getMember(self, name):
if (self.members.has_key(name)):
return self.members[name]
def setMember(self, name, value):
if (self.members.has_key(name)):
self.members[name] = value;
return self.members[name]
def getFormat(self):
return self.fmt
def __len__(self):
return struct.calcsize(self.fmt)
def asBytes(self):
self.bytes = ''
for n,f in self.shape:
if f[-1] == 'x':
self.bytes = self.bytes + struct.pack(f)
else:
self.bytes = self.bytes + struct.pack(f, self.members[n])
return self.bytes
-------------- next part --------------
import isdio
from CStructure import *
class IsdHeader(CStructure):
def __init__(self):
CStructure.__init__(self, (
('len','l'),
('sequence','l'),
('reply','h'),
('error','h'),
('command','h'),
('version','h'),
('workerid','l'),
('more','h'),
('fill','42x')))
self.setMember('len', 0)
self.setMember('sequence', 0)
self.setMember('reply', 0)
self.setMember('error', 0)
self.setMember('command', 0)
self.setMember('version', 0)
self.setMember('workerid', 0)
self.setMember('more', 0)
More information about the Python-list
mailing list