Last active
August 18, 2018 16:18
-
-
Save matutter/068985a8fcec7b6e64a1a18fcc9673a7 to your computer and use it in GitHub Desktop.
Using decorators in python 3
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
| class RouterGuts(object): | |
| def __init__(self, **kwargs): | |
| self.name = kwargs.get('name') | |
| self.route = kwargs.get('route') | |
| def Handler(**kwargs): | |
| def decorateHandlerClass(cls): | |
| guts = RouterGuts(**kwargs) | |
| setattr(cls,'_guts', guts) | |
| return cls | |
| return decorateHandlerClass | |
| class SuperGuard(object): | |
| def __init__(self, **kwargs): | |
| self.var = kwargs.get('var', None) | |
| self.fn = kwargs.get('fn', None) | |
| def __call__(self, fn): | |
| # a function's fully qualified name will contain the classname followed by a "." and the functions name. | |
| is_bound:bool = bool('.' in fn.__qualname__) | |
| def guarded(*args): | |
| if self.fn is not None: | |
| if not self.fn(*args): | |
| print("fn guarded FAIL") | |
| return False | |
| else: | |
| print("fn guard OK") | |
| if is_bound and self.var is not None: | |
| if getattr(args[0], self.var, False): | |
| print("var guarded", self.var) | |
| return False | |
| fn(*args) | |
| return guarded | |
| @Handler(name='a', route='/home/a.html') | |
| class A: | |
| def __init__(self): | |
| self.enabled = False | |
| self.xenabled = False | |
| def checkRun(self): | |
| return True | |
| @SuperGuard(fn=checkRun) | |
| def run2(self): | |
| print("running", 2) | |
| @SuperGuard(var='xenabled') | |
| def run(self, text="000"): | |
| print("running", text) | |
| @SuperGuard(fn=lambda: False) | |
| def normalfn(): | |
| print("run normal fn") | |
| @SuperGuard(var="xxx") | |
| def normalfn2(): | |
| print("run normal fn2") | |
| if __name__ == "__main__": | |
| a = A() | |
| a.run() | |
| a.enabled = True | |
| a.run("abc") | |
| a.run2() | |
| normalfn() | |
| normalfn2() | |
| print(A._guts.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment