OLD | NEW |
(Empty) | |
| 1 from __future__ import absolute_import |
| 2 |
| 3 import collections |
| 4 |
| 5 from .cache import Cache |
| 6 |
| 7 |
| 8 class LFUCache(Cache): |
| 9 """Least Frequently Used (LFU) cache implementation.""" |
| 10 |
| 11 def __init__(self, maxsize, missing=None, getsizeof=None): |
| 12 Cache.__init__(self, maxsize, missing, getsizeof) |
| 13 self.__counter = collections.Counter() |
| 14 |
| 15 def __getitem__(self, key, cache_getitem=Cache.__getitem__): |
| 16 value = cache_getitem(self, key) |
| 17 self.__counter[key] -= 1 |
| 18 return value |
| 19 |
| 20 def __setitem__(self, key, value, cache_setitem=Cache.__setitem__): |
| 21 cache_setitem(self, key, value) |
| 22 self.__counter[key] -= 1 |
| 23 |
| 24 def __delitem__(self, key, cache_delitem=Cache.__delitem__): |
| 25 cache_delitem(self, key) |
| 26 del self.__counter[key] |
| 27 |
| 28 def popitem(self): |
| 29 """Remove and return the `(key, value)` pair least frequently used.""" |
| 30 try: |
| 31 (key, _), = self.__counter.most_common(1) |
| 32 except ValueError: |
| 33 raise KeyError('%s is empty' % self.__class__.__name__) |
| 34 else: |
| 35 return (key, self.pop(key)) |
OLD | NEW |