Python Forum
How to print cache from Decorators with Memoization
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print cache from Decorators with Memoization
#1
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!
Reply
#2
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).
Reply
#3
snippsat, thank you very much for info about __closure__. It's exactly what i need!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable Scopes Decorators oclmedyb 6 827 Jan-15-2021, 02:13 PM
Last Post: oclmedyb
  main libvlc error: stale plugins cache: schascheck 2 2,608 Dec-27-2020, 05:24 PM
Last Post: schascheck
  Decorators and return statements JonEdward 2 806 Jul-24-2020, 05:02 PM
Last Post: JonEdward
  Clear Cache Path sportcardinal 0 662 Jul-05-2020, 05:11 PM
Last Post: sportcardinal
  Python decorators. dodiko1d 0 702 Oct-13-2019, 10:23 AM
Last Post: dodiko1d
  pip cache millpond 3 6,278 Jul-22-2019, 01:12 AM
Last Post: millpond
  python cache for small integer Uchikago 1 1,282 Jun-27-2019, 05:32 PM
Last Post: ichabod801
  Error in request, cache key a21250450 2 1,707 Apr-02-2019, 11:20 AM
Last Post: a21250450
  Decorators yksingh1097 2 1,383 Aug-14-2018, 01:44 PM
Last Post: yksingh1097
  learning decorators Prince_Bhatia 6 1,742 Aug-13-2018, 02:28 PM
Last Post: Prince_Bhatia

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020