Skip to content

Instantly share code, notes, and snippets.

@IwoHerka
Last active July 3, 2018 18:52
Show Gist options
  • Save IwoHerka/4f2fc5ede12e8f3560faa4c91c57bd7e to your computer and use it in GitHub Desktop.
Save IwoHerka/4f2fc5ede12e8f3560faa4c91c57bd7e to your computer and use it in GitHub Desktop.
Class decorator for declaring delegated methods
class Delegated(object):
def __init__(self, delegated_name, attr):
self.attr_name = attr
self.delegated_name = delegated_name
def __get__(self, instance, owner):
if instance is None:
return self
else:
return getattr(self.delegate(instance), self.attr_name)
def __set__(self, instance, value):
setattr(self.delegate(instance), self.attr_name, value)
def __delete__(self, instance):
delattr(self.delegate(instance), self.attr_name)
def delegate(self, instance):
return getattr(instance, self.delegated_name)
class delegate(object):
def __init__(self, src, *attrs):
self.src = src
self.attrs = attrs
def __call__(this, cls):
for attr in this.attrs:
setattr(cls, attr, Delegated(this.src, attr))
return cls
class Bar:
def grok(self):
return 'grok'
@delegate('bar', 'grok')
class Foo:
def __init__(self):
self.bar = Bar()
foo = Foo()
foo.grok()
# 'grok'
foo.grok = 'bar'
foo.grok
# 'bar'
@IwoHerka
Copy link
Author

IwoHerka commented Jul 3, 2018

Similar to def_delegator in Ruby, allows to forward/delegate attributes and methods to some attribute on the object.
Supports setting and deleting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment