Python functools.lru_cache 驱逐回调或等效函数

Iul*_*ian 5 python python-3.x functools

是否可以定义functools.lru_cache一个项目被驱逐时的回调?在回调中还应该存在缓存的值。

如果没有,也许有人知道一个支持驱逐和回调的轻量级类似字典的缓存?

Iul*_*ian 8

我将我使用的解决方案发布出来以供将来参考。我使用了一个名为cachetools的包(https://github.com/tkem/cachetools)。您可以简单地安装$ pip install cachetools

它还具有类似于 Python 3 的装饰器functools.lru_cache( https://docs.python.org/3/library/functools.html )。

不同的缓存都派生自驱逐项目时cachetools.cache.Cache调用popitem()函数的地方。MutableMapping该函数返回“弹出”项的键和值。

要注入逐出回调,只需从所需的缓存中派生并重写该popitem()函数即可。例如:

class LRUCache2(LRUCache):
    def __init__(self, maxsize, missing=None, getsizeof=None, evict=None):
        LRUCache.__init__(self, maxsize, missing, getsizeof)
        self.__evict = evict

    def popitem(self):
        key, val = LRUCache.popitem(self)
        evict = self.__evict
        if evict:
            evict(key, val)
        return key, val
Run Code Online (Sandbox Code Playgroud)