Skip to content

Instantly share code, notes, and snippets.

@viveksoundrapandi
Last active May 19, 2020 08:36
Show Gist options
  • Save viveksoundrapandi/74878a3fbf21818a9c45594ec158c9c0 to your computer and use it in GitHub Desktop.
Save viveksoundrapandi/74878a3fbf21818a9c45594ec158c9c0 to your computer and use it in GitHub Desktop.
Forwardable in python
class Forwardable(object):
def __init__(self, *args, **kwargs):
self._delegates = []
return super().__init__(*args, **kwargs)
@property
def delegates(self):
return self._delegates
@delegates.setter
def delegates(self, delegates):
self._delegates = delegates
def __getattr__(self, name):
#iterate through to delegate items
for attr in self.delegates:
#check if the current lookedup attribute is in any of the delegates
if name == attr[1] and hasattr(getattr(self, attr[0]), attr[2]):
#delegate the call to composed object
return getattr(getattr(self, attr[0]), attr[2])
#raise AttributeError to mimick system default
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))
class Queue(Forwardable):
def __init__(self):
self.q = []
self.delegates = [("q","enqueue", "append")]
que = Queue()
que.enqueue(1)
print que.q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment