Hooking Functions
Hook() class
class Hook():
def __init__(self, origf, hookf):
# Initialize the Hook object
self.origf = origf
self.hookf = hookf
def __call__(self, *args):
# Call the hook function before the original function and pass the same arguments
self.hookf(*args)
# Return the result of the original function
return self.origf(*args)
# func = Hook(func, func_hook)
Example usage
def add(*numbers):
s = 0
for number in numbers:
s += number
return s
def add_hook(*args):
print(*args)
add = Hook(add, add_hook)
print(add(1, 2, 3))
OUTPUT:
1 2 3
6
In this example I hooked a simple function that is returning the sum of some numbers.
You can use the same method to hook any function you want.