Last active
August 29, 2015 14:23
-
-
Save curzona/c50c5fce0f42a0f7eae9 to your computer and use it in GitHub Desktop.
Add callbacks to any function in python
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
| 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