2015-04-06 58 views

回答

2

我将发布我用于未来参考的解决方案。我使用了一个名为cachetools的包(https://github.com/tkem/cachetools)。您只需安装$ pip install cachetools

它也有类似Python 3的装饰器functools.lru_cachehttps://docs.python.org/3/library/functools.html)。

不同的高速缓存都来自cachetools.cache.Cache,它在调出项目时调用MutableMappingpopitem()函数。该函数返回“弹出”项的键和值。

要注入驱逐回调函数,只需从想要的高速缓存中派生并覆盖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