Python functools.lru_cache eviction callback or equivalent

天大地大妈咪最大 提交于 2019-12-23 20:21:08

问题


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.

If not, maybe someone knows a light-weight dict-like cache that supports eviction and callbacks?


回答1:


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.

It also has decorators similar to the Python 3 functools.lru_cache (https://docs.python.org/3/library/functools.html).

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.

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


来源:https://stackoverflow.com/questions/29470958/python-functools-lru-cache-eviction-callback-or-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!