Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'Foundation for rolling your own LRU cache variants'
- import collections
- class LRU:
- def __init__(self, func, maxsize=128):
- self.cache = collections.OrderedDict()
- self.func = func
- self.maxsize = maxsize
- def __call__(self, *args):
- cache = self.cache
- if args in cache:
- cache.move_to_end(args)
- return cache[args]
- result = self.func(*args)
- cache[args] = result
- if len(cache) > self.maxsize:
- cache.popitem(last=False)
- return result
- if __name__ == '__main__':
- f = LRU(ord, maxsize=3)
- for c in 'ABCDCE':
- print('%s -> %s\t\t%r' % (c, f(c), f.cache))
- f.cache.pop(('C',), None) # invalidate 'C'
- print(f.cache)
- f.cache.clear()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement