LRU: 最近最少使用
#!/usr/bin/env python
# encoding: utf-8
from collections import OrderedDict
class LRU(object):
"""Limit size, evicting the least recently looked-up key when full"""
__slots__ = ['maxsize', 'cache']
def __init__(self, maxsize=2000):
self.maxsize = maxsize
self.cache = OrderedDict()
def move_to_end(self, key):
value = self.cache.pop(key)
self.cache[key] = value
def __getitem__(self, key):
value = self.cache[key]
self.move_to_end(key)
return value
def __setitem__(self, key, value=None):
if key in self.cache:
self.move_to_end(key)
self.cache[key] = value
while len(self.cache) > self.maxsize:
self.cache.popitem(last=False)
def __str__(self):
return self.cache.__str__()
def __contains__(self, item):
if item in self.cache:
self.move_to_end(item)
return True
return False
def __iter__(self):
return self.cache.__iter__()
def __len__(self):
return self.cache.__len__()
def __delitem__(self, key):
return self.cache.__delitem__(key)
def setdefault(self, key, value=None):
if key not in self.cache:
self[key] = value
return value
return self.cache[key]
def clear(self):
self.cache.clear()
def items(self):
return self.cache.items()
def iteritems(self):
return self.cache.iteritems()
def pop(self, key):
return self.cache.pop(key)
if __name__ == '__main__':
cache = LRU(maxsize=3)
cache['a'] = 1
cache['b'] = 2
cache['c'] = 3
print(cache) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(cache['a']) # 1
print(cache) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
cache['e'] = 12
print(cache) # OrderedDict([('c', 3), ('a', 1), ('e', 12)])
if 'c' in cache:
print 'hit'
print(cache) # OrderedDict([('a', 1), ('e', 12), ('c', 3)])
cache['z'] = 11
print(cache) # OrderedDict([('e', 12), ('c', 3), ('z', 11)])
参考:
https://github.com/amitdev/lru-dict
GitHub - jlhutch/pylru: A least recently used (LRU) cache for Python