Some background: We have a system for transactions where we devide the flow based upon the country the transaction bills to. We have a logging table that exists in 2 instances, one DB logging transactions to the EU, the other to anywhere else. We also have a test library that manages and hides the guts of working with the DB where roughly speaking each table is represented by a class. I have a class that represents the table, and the db session manager class has two members for each of the two instances of the class. What I want to do is create a generic 'meta dao' class that will take any arbitrary call to it, inspect the args, and based upon one of the input arguments, subsequently dispatch the call to the correct db instance-representing class instance. I initially thought about just overloading every method, but that's clunky and dirty.
I was looking at using __getattr__
to override the method lookup so that I could then call down to the correct instance based upon the name of the method __getattr__
recieves, but from what I understand, I can't inspect
the incoming method arguments from within __getattr__
, so I can't properly dispatch from within it in this case. Does anyone have any ideas of a different direction I can pursue, or a way to 'inspect' the arguments, not just the method name, from within __getattr__
?
[edit] Here's a genericized version of what I'm talking about:
class BarBase(object):
def __init__(self, x):
self.x = x
def do_bar(self, i):
return self.x * i
class FooBar(BarBase):
def __init__(self, x):
super(FooBar, self).__init__(x)
def do_foo(self, i):
return self.x + i
class MetaFoo(object):
def __init__(self, bar_manager):
self.foo_manager = bar_manager
#something here that will take an arbitrary methodname and args as
#long as args includes a value named i, inspect i, and call
#bar_manager.fooa.[methodname](args) if i < 10,
#and bar_manager.foob.[methodname](args) if i >= 10
class BarManager(object):
def __init__(self):
self.bar_list = {}
def __get_fooa(self):
if 'fooa' not in self.bar_list.keys():
self.bar_list['fooa'] = FooBar('a')
return self.bar_list['fooa']
fooa = property(__get_fooa)
def __get_foob(self):
if 'foob' not in self.bar_list.keys():
self.bar_list['foob'] = FooBar('b')
return self.bar_list['foob']
foob = property(__get_foob)
def __get_foo(self):
if 'foo' not in self.bar_list.keys():
self.bar_list['foo'] = MetaFoo(self)
return self.bar_list['foo']