You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
974 B

  1. import random
  2. from .cache import Cache
  3. # random.choice cannot be pickled in Python 2.7
  4. def _choice(seq):
  5. return random.choice(seq)
  6. class RRCache(Cache):
  7. """Random Replacement (RR) cache implementation."""
  8. def __init__(self, maxsize, choice=random.choice, getsizeof=None):
  9. Cache.__init__(self, maxsize, getsizeof)
  10. # TODO: use None as default, assing to self.choice directly?
  11. if choice is random.choice:
  12. self.__choice = _choice
  13. else:
  14. self.__choice = choice
  15. @property
  16. def choice(self):
  17. """The `choice` function used by the cache."""
  18. return self.__choice
  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. msg = '%s is empty' % self.__class__.__name__
  25. raise KeyError(msg) from None
  26. else:
  27. return (key, self.pop(key))