I try to use two different wrappers on a recursive Fibonacci function to: 1) Count the number of recursions, 2) Memoize the computed values to reduce computations needed.
As each wrapping function creates a new function attribute on the created function, after wrapping again I can't access it anymore. Is there a way to still access it without doing a single wrap function with both effects ?
def count(f):
def f1(*args):
f1.counter += 1
return f(*args)
f1.counter = 0
return f1
def memoize(f):
def f1(*args):
if not args in f1.memo:
f1.memo[args] = f(*args)
return f1.memo[args]
f1.memo = {}
return f1
@memoize
@count
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
After this I can access fib.memo but not fib.counter, and conversely if I wrap fib with memoize before count.