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)
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! |