Janek Podwysocki
Janek Podwysocki

Reputation: 593

How to clean (reset) cache memory of my decorator?

I need to write decorator to remember function results for given parameters. I did it, but how to reset the memory? I tried to reset func.cache, but without correct result.

from random import random

    def cached(func):
        cache = func.cache = {}
        func.call_num = 0
        func.eval_num = 0
        def memorised_func(*args, **kwargs):
            key = str(args) + str(sorted(kwargs.items(), key=lambda kv: kv[1]))
            #print(key)
            if key not in cache:
                cache[key] = func(*args, **kwargs)
                func.eval_num += 1
            func.call_num += 1
            print(func.call_num, func.eval_num)
            return cache[key]
        memorised_func.cache_status = lambda: print(f"Function {func.__name__} called {func.call_num} times, evaluated {func.eval_num} times")
        #memorised_func.cache_reset = lambda : func.cache #-TODO , help
        return memorised_func

    @cached
    def foo(x, y=1, z=4):
        return random()

    #EXAMPLE THAT SHOULD WORK    
    print(foo(3) == foo(3))
    print(foo(4) == foo(4))
    print(foo(3, z=-1, y=3) == foo(3, y=3, z=-1))
    print(foo(3) != foo(x=3))
    a = foo(3)
    foo.cache_reset() #HERE DOESN'T WORK - TODO
    print(a != foo(3))
    print(foo.cache_status() == 'Function foo called 10 times, evaluated 5 times')

Upvotes: 3

Views: 1293

Answers (1)

F1Rumors
F1Rumors

Reputation: 948

the commented out section is simply:

memorised_func.cache_reset  = lambda: func.cache.clear()

You have a strong crossover with memoize from the func library, consider looking in to that, too.

Upvotes: 4

Related Questions