I am trying to understand an example of a Fibonacci sequence using a decorator to store values of already calculated numbers. For example fib(5) would be calculated, and when we got to fib(6), it wouldn't calculate fib(5) again...
I understand decorators a little bit, but some things just confuse me. I have a few questions about the code below.
from functools import wraps
def dec(func):
values = {}
@wraps(func)
def wrap(*args):
if args not in values:
values[args] = func(*args)
return values[args]
return wrap
@dec
def fib(n):
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
- Why are
*argsused inwrap()? Isn't it supposed to just take a number n and check if the value of that is in the dictionary? Why areargsin some places called with, and in some without the*? - What happens when the function
fibis called recursively (how does the decorator function behave). I first thought it enters that function during every recursion, but that can't be right because the values dictionary would reset? So does it then enter just thewrap()function? - Why does it return wrap at the end?