Last active
January 9, 2018 23:50
-
-
Save cowbert/eff5c717119cf76f4146d72c413670fc to your computer and use it in GitHub Desktop.
Inherit an argument-accepting method decorator pattern
This file contains hidden or 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
""" | |
I want to enforce coupling between a decorator that takes params and the method | |
it should apply to (invoking the decorator outside of the class would make no | |
semantic sense) | |
""" | |
class Foo(object): | |
attr = ['a','b','c'] | |
def __init__(self, *args, **kwargs): | |
for i, arg in enumerate(args): | |
setattr(self, self.attr[i], arg) | |
@staticmethod | |
def decorator_with_param(*params): | |
def decorator(method): | |
def decorated(self, *args, **kwargs): | |
inst_c = getattr(self, 'c', '') | |
if params and params[0] == inst_c: | |
return method(self, *args, **kwargs) | |
else: | |
return "No" | |
return decorated | |
return decorator | |
class Bar(Foo): | |
# Test inheritance | |
# In my real code, I have RequestHandler -> BaseHandler -> DirectAccessHandler -> RouteHandler | |
def methodA(self, *args, **kwargs): | |
return "Bar's methodA" | |
class Baz(Bar): | |
@Bar.decorator_with_param('go') | |
def methodA(self, *args, **kwargs): | |
return "Yes" | |
if __name__ == '__main__': | |
assert(Baz(1,2,3).methodA()) == "No" | |
assert(Baz(1,2,'go').methodA()) == "Yes" | |
assert(Bar(1,2,3).methodA()) == "Bar's methodA" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment