I am trying to implement a cache with a simple eviction algorithm.
I would like to use cachetools from Python and modify a cache class like LFUCache so that early on the cache accepts all objects and later when the cache is full only objects that are smaller than a given threshold will be cached. The object with the greatest value is evicted.
This is my code so far:
class Thresold_Cache(LRUCache):
def __init__(self, maxsize, getsizeof=None):
super().__init__(maxsize, getsizeof)
def __getitem__(self, key):
value = super().__getitem__(key)
return value
def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
thresold = 15 # let's say the thresold is 15.
if self[key] > thresold or self[key] == thresold:
cache_setitem(self, key, value)
def __delitem__(self, key, cache_delitem=Cache.__delitem__):
cache_delitem(self, key)
def popitem(self):
"""Remove and return the `(key, value)` with max value"""
try:
key = max(self.__data)
except StopIteration:
raise KeyError("%s is empty" % type(self).__name__) from None
else:
return (key, self.pop(key))