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
  Decorators @ annotation drcl 3 337 Feb-24-2024, 06:12 AM
Last Post: Gribouillis
  Does @ at sign used for tother than decorators? ggpython000 1 497 Oct-12-2023, 09:08 AM
Last Post: buran
  Speeding up code using cache Peter 1 512 Jul-29-2023, 04:52 AM
Last Post: bowlofred
  Opinion: how should my scripts cache web download files? stevendaprano 0 704 Dec-17-2022, 12:19 AM
Last Post: stevendaprano
  Variable Scopes Decorators oclmedyb 6 2,669 Jan-15-2021, 02:13 PM
Last Post: oclmedyb
  main libvlc error: stale plugins cache: schascheck 2 7,594 Dec-27-2020, 05:24 PM
Last Post: schascheck
  Decorators and return statements JonEdward 2 1,857 Jul-24-2020, 05:02 PM
Last Post: JonEdward
  Clear Cache Path sportcardinal 0 1,580 Jul-05-2020, 05:11 PM
Last Post: sportcardinal
  Python decorators. dodiko1d 0 6,961 Oct-13-2019, 10:23 AM
Last Post: dodiko1d
  pip cache millpond 3 8,154 Jul-22-2019, 01:12 AM
Last Post: millpond

Forum Jump:

User Panel Messages

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