1import random 2 3from .cache import Cache 4 5 6class RRCache(Cache): 7 """Random Replacement (RR) cache implementation.""" 8 9 def __init__(self, maxsize, choice=random.choice, missing=None, 10 getsizeof=None): 11 Cache.__init__(self, maxsize, missing, getsizeof) 12 self.__choice = choice 13 14 @property 15 def choice(self): 16 """The `choice` function used by the cache.""" 17 return self.__choice 18 19 def popitem(self): 20 """Remove and return a random `(key, value)` pair.""" 21 try: 22 key = self.__choice(list(self)) 23 except IndexError: 24 raise KeyError('%s is empty' % self.__class__.__name__) 25 else: 26 return (key, self.pop(key)) 27