I am reading some binary data from a serial port. Each packet can contain a wide array (a couple of dozen or so) messages identified by specific byte sequences. To make matter simple, let us assume only one bye so that 0x01
corresponds to the first message and so on. I want to be able to call a process
method to deal with each message. I could have a long and tedious if loop but that would be horrid. A singledispatch
seems like a much nicer option but a class per message seems OO gone made as well as getting back to the huge if loop for creating those.
So, I need a single dispatch by value of bytearray
working on methods.
Something like thus:
from functools import singledispatch
class Ook(object):
def __init__(self, *args, **kwargs):
self.process = singledispatch(self.process)
self.process.register(bytearray([0x01]), self.process_msg_one) # FIXME!
self.process.register(bytearray([0x02]), self.process_msg_two) # FIXME!
def process(self, arg):
raise TypeError("Message is not supported.")
def process_msg_one(self, arg):
print(arg)
def process_msg_two(self, arg):
print(arg)
I am well aware of Łukasz Langa's blog post but his implementation of dispatch by value uses Enum
as a base class. My real Ook
class inherits from an abstract class (so I can have a simulator instead of real hardware) and mixing it with Enum
raises TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its base
…