Please help me understand decorators in Python (Fibonnacci + memoization)

I am trying to understand the following code (from this site: http://jeremykun.com/2012/01/12/a-spoonful-of-python/ ):

def memoize(f):
    cache = {}

    def memoizedFunction(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]

    memoizedFunction.cache = cache  
    return memoizedFunction 

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

I understand the advantage of using a cache, for example, to calculate Fibonacci numbers. I also understand that now that I call fib (4), it is equivalent to calling myfun (4), where myfun = memoize (fib).

I don’t understand why the cache is not reassigned {} for each feed call.

Can someone explain?

Thank!

+4
source share
1 answer

memoize , fib . cache ( memoize), fib. fib memoizedFunction, memoize, fib, memoizedFunction , reset.

+5

All Articles