lrucache.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. class LRUCache:
  2. def __init__(self, capacity, dispose):
  3. self._cache = {}
  4. self._lru = []
  5. self._capacity = capacity
  6. self._dispose = dispose
  7. def __setitem__(self, key, value):
  8. assert key not in self._cache, (
  9. "Unexpected attempt to replace a cached item,"
  10. " without first deleting the old item.")
  11. self._lru.append(key)
  12. while len(self._lru) > self._capacity:
  13. del self[self._lru[0]]
  14. self._cache[key] = value
  15. def __getitem__(self, key):
  16. value = self._cache[key] # raise KeyError if not found
  17. self._lru.remove(key)
  18. self._lru.append(key)
  19. return value
  20. def __delitem__(self, key):
  21. value = self._cache.pop(key) # raise KeyError if not found
  22. self._dispose(value)
  23. self._lru.remove(key)
  24. def __contains__(self, key):
  25. return key in self._cache
  26. def clear(self):
  27. for value in self._cache.values():
  28. self._dispose(value)
  29. self._cache.clear()
  30. # useful for testing
  31. def items(self):
  32. return self._cache.items()
  33. def __len__(self):
  34. return len(self._cache)