I'm using python3.7.0 version .I am trying to implement decorator pattern that saved its' result with the dictionary variable cache
def memoize(fn):
cache = dict()
@wraps(fn)
def memoizer(*args,**kwargs):
if args not in cache:
cache[args] = fn(*args,**kwargs)
return cache[args]
return memoizer
@memoize
def fibonacci(n):
'''Returns the suite of Fibonacci numbers'''
assert(n >= 0), 'n must be >= 0'
if n in (0, 1):
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
However, I get confused when I inserted varaible count
in memoize decorator since insert this variable caused UnboundLocalError when calling fibonacci function.
def memoize(fn):
cache = dict()
count = 0
@wraps(fn)
def memoizer(*args,**kwargs):
count += 1
if args not in cache:
cache[args] = fn(*args,**kwargs)
return cache[args]
return memoizer
I couldn't understands why using integer varaible count
with decorator function caused UnboundLocalError
while with dictionary variable cache
isn't?