0

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?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
강희명
  • 143
  • 1
  • 3
  • 9
  • Possible duplicate of [Don't understand why UnboundLocalError occurs](https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs) – Zero Piraeus Dec 23 '18 at 10:38
  • See [Why am I getting an UnboundLocalError when the variable has a value?](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) at the Python Programming FA. – Zero Piraeus Dec 23 '18 at 10:39
  • In this case, you would add the line `nonlocal count` before `count += 1` to indicate to Python that you're referring to the `count` variable defined in `memoize()`, rather than creating a new variable local to `memoizer()`. – Zero Piraeus Dec 23 '18 at 10:43
  • 2
    And the answer to why the behaviour is different is because you're doing different things: mutating vs reassigning. – Daniel Roseman Dec 23 '18 at 10:45

0 Answers0