Last active
September 15, 2019 16:28
-
-
Save purarue/ae69d69772a7a6ab089ebeb87a1ce3b4 to your computer and use it in GitHub Desktop.
Testing a hack around an existing library, to add pre/post hooks to functions
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 Library: | |
def a(self, n): | |
print('a' * n) | |
def b(self, n): | |
print('b' * n) | |
class Extender(Library): | |
overwritten_methods = ['a'] | |
def __init__(self, pre_hook): | |
super().__init__() | |
self.pre_hook = pre_hook | |
def __getattribute__(self, name): | |
if name in Extender.overwritten_methods: | |
def func(*args, **kwargs): | |
# pre-hooks | |
self.pre_hook[name](kwargs.get('n', None)) | |
resp = getattr(super(Extender, self), name)(*args, **kwargs) | |
# post-hooks | |
print("post-hook") | |
return resp | |
return func | |
else: | |
return object.__getattribute__(self, name) | |
log = {"a": lambda num: print("'a' called with", num)} | |
if __name__ == "__main__": | |
e = Extender(pre_hook=log) | |
e.a(n=5) | |
e.b(n=6) | |
""" | |
Output: | |
'a' called with 5 | |
aaaaa | |
post-hook | |
bbbbbb | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment