I'm trying to do protocol decoding in Python.
Short version of my question:
I have received an array of bytes that is a packet of data.
- Using the first byte of the packet, I know what type of packet it is.
- Using that - I want to construct a packet via a class.
When i want to send a packet, really need to reuse about 90% of the processing done in the same packet class so that I can construct and send a packet.
I can do one of the above, I can't seem to do both
For example - something like this:
class PacketType123(BasePacketType):
def __init__fromparams( self, field1, field2 ):
# called when you want to send a packet
# ... initialize like I'am sending the packet
self.field1 = field1
self.field2 = field2
def encode_and_send(self,destination):
# encode into raw byte
databytes = self.encode()
destination.send( databytes )
# called when a packet is received on the wire
def __init__frombytearray( self, bytearray ):
self.decode_bytearray( bytearray )
print("Hi Field2 = %d" % self.field2 )
# create packet decode lookup table.
lookuptable = dict()
# populate it with classes
lookuptable[123] = PacketType123
# other packets would added to the lookup table
lookuptable[44] = PacketType44
lookuptable[12] = PacketType12
To send
p1 = PacketType1( 42, "dogs and cats" )
p1.encode_and_send( server )
To process incomming data, do this:
databytes = receive_message()
packet = lookuptable[ datbytes[0] ].__init__frombytearray(databytes)
My problem is I can do either the ToSend or the ProcessIncomming, I don't know how to do both with the same class.
I've looked over:
- May __init__ be used as normal method for initialization, not as constructor?
- Multiple constructors in python?
What is a clean, pythonic way to have multiple constructors in Python?
I've seen this but I'm confused by it: https://hg.python.org/cpython/file/3.5/Lib/multiprocessing/heap.py#l223
It seems the only way to make this work is with keyword args.. Yuck that complicates other things for me... Looking for other way of doing this.
Suggestions please?
BasePacketTypeclass, your specific classes would inherit from that class, which will implement the specific constructors (i.e. the keyword arguments). Your question is how to turn abytearrayautomagically into the correct subclass?AutoPacket(some_bytearray), if thesome_bytearrayis decoded into something that has been registered into the lookup table, it will then produce the correct type, e.g. it would producePacketType1withfield1set to42andfield2set to"dogs and cats". Let us know if this is closer to to how you imagine this API might appear.decode_bytearrayand__init__frombytearrayasclassmethod, and thatdecode_bytearrayneed to return something rather than setting some attributes inside the implementation. It would be useful to include what your current implementation is for the line that invokedself.decode_bytearray( bytearray ).