Reputation: 280
Is there a way to easily expose the APi of an internal object of a python class without retyping every API of that object? For example, I write a redis replica class and all my functions are like
def get_connection(self, name):
........
host, conn = self.colo_rings[name]
return conn
def hgetall(self, name):
return self.get_connection(name).hgetall(name)
def hset(self, name, key, value):
return self.get_connection(name).hset(name, key, value)
def hsetnx(self, name, key, value):
return self.get_connection(name).hsetnx(name, key, value)
def hdel(self, name, *key, colo=None):
return self.get_connection(name).hdel(name, *key)
How can I improve this code and make it not that "ugly"?
Upvotes: 1
Views: 255
Reputation: 47988
You should be able to use something similar to this:
class B(object):
def __getattribute__(self, method):
try:
return getattr(self, method)
except:
return getattr(self.get_connection(key), method)
The advantage here is that you can still use methods that don't exist on your connection by defining them on the class, but anything that you don't define and that exists on the connection will be used when you try to access it via myB.hgetall()
(for example).
For completeness - __getattr__
is sufficient:
class B(object):
def __getattr__(self, method):
return getattr(self.get_connection(key), method)
Upvotes: 1