Skip to content

Instantly share code, notes, and snippets.

@curzona
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save curzona/c50c5fce0f42a0f7eae9 to your computer and use it in GitHub Desktop.

Select an option

Save curzona/c50c5fce0f42a0f7eae9 to your computer and use it in GitHub Desktop.
Add callbacks to any function in python
from __future__ import print_function
class Watcher(object):
def __init__(self, func):
self.func = func
self.before = []
self.after = []
def __call__(self, *args, **kargs):
for callback in self.before:
callback(*args, **kargs)
retval = self.func(*args, **kargs)
for callback in self.after:
callback(*args, **kargs)
def foo():
print("foo")
foo = Watcher(foo)
foo.before.append(lambda: print("before"))
foo.after.append(lambda: print("after"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment