I am trying to figure out the most Pythonic way to pass in a limited callback for interacting with a complicated object's methods. I have a program which receives data over a communications channel, and that data falls into a few different categories. I need to decouple the determination of which category the data is in, from the further handling of the data:
class Categorizer(object):
'''Determines which category data is in.
There may be multiple variants of this class'''
def handleData(self, data, callback):
if self.somethingReallySpecial(data):
callback.onSomethingReallySpecial(data)
elif self.somethingSpecial(data):
callback.onSomethingSpecial(data)
else:
callback.onSomethingMundane(data)
# ... other methods ...
class IAmAReallyComplicatedBeast(object):
def __init__(self, categorizer, other_stuff):
self.categorizer = categorizer
# ...
# ... lots of other methods ...
def something(self, other_stuff):
data = self.obtain_data()
# this is probably wrong, but here's what I want to do:
beast = self
class Dispatcher(object):
def onSomethingMundane(data):
beast.doFoo(data)
def onSomethingSpecial(data):
beast.doBar(data)
def onSomethingReallySpecial(data):
beast.doBaz(data)
self.categorizer.handleData(data, Dispatcher())
def doFoo(self, data):
# for mundane data
def doBar(self, data):
# for special data
def doBaz(self, data):
# for really special data
In Java I would use an inner class (like the Dispatcher here)... is there a Pythonic way of handling this?
I don't want to put the onSomethingXXX
methods directly on my IAmAReallyComplicatedBeast
class, for two reasons:
- this means I'd have to use those names as is
- I don't want the
Categorizer
class to have arbitrary access to theIAmAReallyComplicatedBeast
object. Perhaps this comes from the usual Java paranoia mindset, but it seems like good design to me.