0

Can someone explain the code snippet below? I'm a bit confused by the syntax @memoize. When/how is it called? What does it do?

import functools

def memoize(fn):
    known = dict()

    @functools.wraps(fn)
    def memoizer(*args):
        if args not in known:
            known[args] = fn(*args)
        return known[args]

    return memoizer

@memoize
def fibonacci(n):
    '''Returns the nth number of the Fibonacci sequence'''
    assert(n >= 0), 'n must be >= 0'
    return n if n in (0, 1) else fibonacci(n-1) + fibonacci(n-2)

if __name__ == '__main__':
    print(fibonacci(10))
Alex Dicianu
  • 349
  • 2
  • 9
  • it's called during code load. it's the same as having: def fibonacci(n): # etc pass fibonacci = memoize(fibonacci) – mephisto Dec 15 '15 at 15:21
  • 1
    Are you confused about decorators in general or the memoization one? I'm asking because you're basically asking, "What does this code do?" Which is too broad. There are a lot of resources online explaining decorators, and [here is](http://stackoverflow.com/q/1988804/2615940) a SO question about memoization. – skrrgwasme Dec 15 '15 at 15:22
  • 1
    ``memoize`` caches the values of the fibonacci computation. if the values were computed before, it returns them from the dict ``known`` and doesn't recompute them. – lgd Dec 15 '15 at 15:26
  • I was pretty much confused about when and how the function `memoize` is getting called. I read the decorators docs a bunch of times, but the language isn't extremely clear (at least not to me). – Alex Dicianu Dec 15 '15 at 15:41
  • @AlexDicianu by decorating `fibonacci` with `@memoize` you are actually binding the fibonacci name/variable to the function returned by `memoize(fibonacci)`. So `memoizer` is "implicitly" called every time you call `fibonacci`, while `memoize` is called one time when defining `fibonacci` – LeartS Dec 15 '15 at 15:55

1 Answers1

4
@memoize
def fibonacci(n):
    ...

Is the same thing as

def fibonacci(n):
    ...

fibonacci = memoize(fibonacci)

See this stack overflow answer for a detailed explanation on how decorators work.

wp-overwatch.com
  • 6,475
  • 3
  • 34
  • 43