lrucache.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from heapq import heappush, heapify, heapreplace, heappop
  2. class LRUCache(dict):
  3. def __init__(self, capacity):
  4. super(LRUCache, self).__init__()
  5. self._lru = []
  6. self._capacity = capacity
  7. def __setitem__(self, key, value):
  8. try:
  9. self._lru.remove(key)
  10. except ValueError:
  11. pass
  12. self._lru.append(key)
  13. while len(self._lru) > self._capacity:
  14. del self[self._lru[0]]
  15. return super(LRUCache, self).__setitem__(key, value)
  16. def __getitem__(self, key):
  17. try:
  18. self._lru.remove(key)
  19. self._lru.append(key)
  20. except ValueError:
  21. pass
  22. return super(LRUCache, self).__getitem__(key)
  23. def __delitem__(self, key):
  24. try:
  25. self._lru.remove(key)
  26. except ValueError:
  27. pass
  28. return super(LRUCache, self).__delitem__(key)
  29. def pop(self, key, default=None):
  30. try:
  31. self._lru.remove(key)
  32. except ValueError:
  33. pass
  34. return super(LRUCache, self).pop(key, default)
  35. def _not_implemented(self, *args, **kw):
  36. raise NotImplementedError
  37. popitem = setdefault = update = _not_implemented