Advertisement
raymondh

LRU Cache Foundation

Sep 17th, 2016
4,084
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. 'Foundation for rolling your own LRU cache variants'
  2.  
  3. import collections
  4.  
  5. class LRU:
  6.  
  7.     def __init__(self, func, maxsize=128):
  8.         self.cache = collections.OrderedDict()
  9.         self.func = func
  10.         self.maxsize = maxsize
  11.  
  12.     def __call__(self, *args):
  13.         cache = self.cache
  14.         if args in cache:
  15.             cache.move_to_end(args)
  16.             return cache[args]
  17.         result = self.func(*args)
  18.         cache[args] = result
  19.         if len(cache) > self.maxsize:
  20.             cache.popitem(last=False)
  21.         return result
  22.  
  23. if __name__ == '__main__':
  24.  
  25.     f = LRU(ord, maxsize=3)
  26.     for c in 'ABCDCE':
  27.         print('%s -> %s\t\t%r' % (c, f(c), f.cache))
  28.     f.cache.pop(('C',), None)          # invalidate 'C'
  29.     print(f.cache)
  30.     f.cache.clear()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement