Python Forum
How to print cache from Decorators with Memoization - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to print cache from Decorators with Memoization (/thread-24051.html)



How to print cache from Decorators with Memoization - OlgaM - Jan-28-2020

Hello!

I use this decorator for memoization. But how i can check if results number is really cached?
When i try to print fib.cache or cache[n] i got error: cache is not defined.
How can i print cache dictionary and check if it's really working?

def memoize(f):
    cache = {}
    def decorate(*args):
        if args not in cache:
           cache[args] = f(*args)
        return cache[args]
    return decorate

@memoize
def fib(n):
    assert n >=0
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)
Thank you!


RE: How to print cache from Decorators with Memoization - snippsat - Jan-29-2020

Can use __closure__ attribute.
def memoize(f):
    cache = {}
    def decorate(*args):
        if args not in cache:
           cache[args] = f(*args)
        return cache[args]
    return decorate

@memoize
def fib(n):
    assert n >=0
    if n < 2:
        return n
    else:
        return fib(n-1) + fib(n-2)

print(fib(35))
print(fib.__closure__[0].cell_contents)
Output:
9227465 {(1,): 1, (0,): 0, (2,): 1, (3,): 2, (4,): 3, (5,): 5, (6,): 8, (7,): 13, (8,): 21, (9,): 34, (10,): 55, (11,): 89, (12,): 144, (13,): 233, (14,): 377, (15,): 610, (16,): 987, (17,): 1597, (18,): 2584, (19,): 4181, (20,): 6765, (21,): 10946, (22,): 17711, (23,): 28657, (24,): 46368, (25,): 75025, (26,): 121393, (27,): 196418, (28,): 317811, (29,): 514229, (30,): 832040, (31,): 1346269, (32,): 2178309, (33,): 3524578, (34,): 5702887, (35,): 9227465}
OlgaM Wrote:check if it's really working?
It working try comment out #@memoize then call fib(40).


RE: How to print cache from Decorators with Memoization - OlgaM - Jan-29-2020

snippsat, thank you very much for info about __closure__. It's exactly what i need!