Skip to content

Instantly share code, notes, and snippets.

@kkew3
Created December 22, 2018 10:46
Show Gist options
  • Save kkew3/2d61463397a77a898be12ac766c31c12 to your computer and use it in GitHub Desktop.
Save kkew3/2d61463397a77a898be12ac766c31c12 to your computer and use it in GitHub Desktop.
Python delegate decorator
def delegates(method_names, to):
def dm(method_name):
def fwraps(self, *args, **kwargs):
wrappedf = getattr(getattr(self, to), method_name)
return wrappedf(*args, **kwargs)
fwraps.__name__ = method_name
return fwraps
def cwraps(cls):
for name in method_names:
setattr(cls, name, dm(name))
return cls
return cwraps
# Usage
class A(object):
def method_a(self, *args, **kwargs):
pass
def method_b(self, *args, **kwargs):
pass
@delegates(['method_a', 'method_b'], to='a')
class B(object):
def __init__(self):
self.a = A()
b = B()
b.method_a(...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment