2015-04-06 61 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