I am playing with cache functions using decorators.First, I use a generic functiondef memorize(func):    cache = {}    print printing cache    print cache    print cache printed        def decor_func(*args):        if args in cache:            print cached value is found            return cache[args]        else:            print calculating the value            val = func(*args)            cache[args] = val            return val    return decor_funcThen I use it to decorate a function called testdef test(n):    return ntest_decorated = memorize(test)Then I get the following results>>> test_decorated(1)calculating the value1>>> test_decorated(2)calculating the value2>>> test_decorated(1)cached value is found1>>>You can see that the second test_decorated(1) won't actually do any calculation, because we have already cache the result.Now I want understand further, so I definedef test_cached(n):    cache = {}    print printing cache    print cache    print cache printed        if n in cache:        print cached value is found        return cache[n]    else:        print calculating the value        val = n        cache[n] = val        return valI thought that I will get the same results as above when I call test_cached.However, the answer is NO, and the function test_cached didn't remember any calculated values. Here is the result:>>> test_cached(1)printing cache{}cache printedcalculating the value1>>> test_cached(2)printing cache{}cache printedcalculating the value2>>> test_cached(1)printing cache{}cache printedcalculating the value1>>> As you can see, the second test_cached(1) re-calculate again the result.I would like to know why these two approaches give different results, i.e.why the first approach successfully caches the results, but the second fails
Python - Cache function and decorator
python;caching;decorator