Python functools.lru_cache 驱逐回调或等效

Python functools.lru_cache eviction callback or equivalent

是否可以在项目被逐出时为 functools.lru_cache 定义回调?在回调中,缓存的值也应该存在。

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

我将post我使用的解决方案以备将来参考。我使用了一个名为 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,它在逐出项目时从 MutableMapping 调用 popitem() 函数。此函数 returns "popped" 项的键和值。

要注入逐出回调,只需从所需的缓存中派生并覆盖 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