Skip to content

Instantly share code, notes, and snippets.

@phalt
Created November 9, 2014 19:58
Show Gist options
  • Save phalt/c6ea9e180e9c3bfbcd35 to your computer and use it in GitHub Desktop.
Save phalt/c6ea9e180e9c3bfbcd35 to your computer and use it in GitHub Desktop.
LRU Cache
class LRUCache(object):
""" Implements a least-recently-used cache in Python
As the cache grows it will cap at some fixed size described by the max_size
property
When you attempt to add a new object into a full cache, it will discard the
Least Recently Used cached item.
Calling set('key', ...) or get('key') constitutes a "use" of 'key'
Usage:
cache = LRUCache()
cache.set('foo', some_complex_object())
print cache.get('foo')
"""
def __init__(self, max_size=10):
self.max_size = max_size
self.cache = {}
self.order = []
def set(self, key, value):
current_size = len(self.order)
if self.max_size >= current_size:
del self.cache[self.order(current_size)]
del self.order[current_size]
self.cache[key] = value
self.order.insert(0, key)
def get(self, key):
if key in self.cache:
self.order.insert(0, key)
return self.cache[key]
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment