Python Forum

Full Version: Help... python decorator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a python function and a decorator that works just fine and it looks like this:
def fun_cache(function): 
   memo = {} 
   def wrapper(*args): 
       if args in memo: 
           return memo[args] 
       else: 
           rv = function(*args) 
           memo[args] = rv 
           return rv 
   return wrapper 


@fun_cache 
def fib(n): 
   if (n < 2): return 1 
   else: return fib(n-1) + fib(n-2) 

assert(fib(0) == 1) 
assert(fib(3) == 3) 
assert(fib(6) == 13) 
assert(fib(10) == 89) 
assert(fib(30) == 1346269) 
assert(fib(100) == 573147844013817084101) 
assert(fib(400) == 284812298108489611757988937681460995615380088782304890986477195645969271404032323901) 
Now I will like to call the @fun_cache decorator like this :
@fun_cache(memo={}) 
def fib(n): 
   if (n < 2): return 1 
   else: return fib(n-1) + fib(n-2) 
Any help?

***SOLVED***

I was able to figure it out after reading some other forums. I wrote a "fun_cache" function accepting a cache argument.