How can I wrap a recursive function, including recursive calls? For example, given foo and wrap :
def foo(x): return foo(x - 1) if x > 0 else 1 def wrap(f): def wrapped(*args, **kwargs): print "f was called" return f(*args, **kwargs) return wrapped
wrap(foo)(x) will only output "f was called" on the first call. Recursive calls are still addressed to foo() .
I do not mind monkey patches or shaking around internal organs. I do not plan to add this code to the next nuclear warhead processing program, so even if this is a bad idea, I would like to achieve an effect.
Edit : for example, fix foo.func_globals to override foo.__name__ ? If this is always the case, are there any side effects that I should remember?
slezica
source share