Python Forum
python decorator - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: python decorator (/thread-2143.html)



python decorator - alfredocabrera - Feb-22-2017

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.

Mekire:
Moderator: Just because he solved his own problem doesn't mean the thread should be deleted.