问题描述
是否可以在逐出项目时为functools.lru_cache
定义回调?在回调中,还应该存在缓存的值.
Is it possible to define a callback for functools.lru_cache
when an item is evicted? In the callback the cached value should also be present.
如果没有,也许有人知道像轻量级的类似dict的缓存,该缓存支持逐出和回调?
If not, maybe someone knows a light-weight dict-like cache that supports eviction and callbacks?
推荐答案
我将发布用于以后参考的解决方案.我使用了一个名为cachetools的软件包( https://github.com/tkem/cachetools ).您可以简单地通过$ pip install cachetools
进行安装.
I will post the solution I used for future reference. I used a package called cachetools (https://github.com/tkem/cachetools). You can install by simply $ pip install cachetools
.
它也具有类似于Python 3 functools.lru_cache
的装饰器( https://docs .python.org/3/library/functools.html ).
It also has decorators similar to the Python 3 functools.lru_cache
(https://docs.python.org/3/library/functools.html).
不同的缓存全部来自cachetools.cache.Cache
,当逐出一个项目时,cachetools.cache.Cache
从MutableMapping
调用popitem()
函数.此函数返回键和弹出"项的值.
The different caches all derive from cachetools.cache.Cache
which calls the popitem()
function from MutableMapping
when evicting an item. This function returns the key and the value of the "popped" item.
要插入驱逐回调,只需从所需的缓存派生并覆盖popitem()
函数.例如:
To inject an eviction callback one simply has to derive from the wanted cache and override the popitem()
function. For example:
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
这篇关于Python functools.lru_cache逐出回调或等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!