Created
December 22, 2018 10:46
-
-
Save kkew3/2d61463397a77a898be12ac766c31c12 to your computer and use it in GitHub Desktop.
Python delegate decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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