Skip to content

Instantly share code, notes, and snippets.

@purarue
Last active September 15, 2019 16:28
Show Gist options
  • Save purarue/ae69d69772a7a6ab089ebeb87a1ce3b4 to your computer and use it in GitHub Desktop.
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
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