我需要编写装饰器来记住给定参数的函数结果。我做到了,但是如何重置内存?我试图重置func.cache,但是没有正确的结果。

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

最佳答案

注释掉的部分很简单:

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


您在memoize库中与func有很强的交叉,也可以考虑一下。

关于python - 如何清理(重置)我的装饰器的缓存?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58626079/

10-14 04:50