forked from stucchio/Python-LRU-cache
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlru.py
185 lines (164 loc) · 4.93 KB
/
lru.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from collections import OrderedDict
from time import time
from itertools import islice
def lru_cache_function(max_size=1024, expiration=15*60):
"""
>>> @lru_cache_function(3, 1)
... def f(x):
... print "Calling f(" + str(x) + ")"
... return x
>>> f(3)
Calling f(3)
3
>>> f(3)
3
"""
def wrapper(func):
return LRUCachedFunction(func, LRUCacheDict(max_size, expiration))
return wrapper
class LRUCacheDict(object):
""" A dictionary-like object, supporting LRU caching semantics.
>>> d = LRUCacheDict(max_size=3, expiration=3)
>>> d['foo'] = 'bar'
>>> d['foo']
'bar'
>>> import time
>>> time.sleep(4) # 4 seconds > 3 second cache expiry of d
>>> d['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
>>> d['a'] = 'A'
>>> d['b'] = 'B'
>>> d['c'] = 'C'
>>> d['d'] = 'D'
>>> d['a'] # Should return value error, since we exceeded the max cache size
Traceback (most recent call last):
...
KeyError: 'a'
"""
def __init__(self, max_size=1024, expiration=15*60):
self.max_size = max_size
self.expiration = expiration
self.__values = {}
self.__expire_times = OrderedDict()
self.__access_times = OrderedDict()
def size(self):
return len(self.__values)
def clear(self):
"""
Clears the dict.
>>> d = LRUCacheDict(max_size=3, expiration=1)
>>> d['foo'] = 'bar'
>>> d['foo']
'bar'
>>> d.clear()
>>> d['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
"""
self.__values.clear()
self.__expire_times.clear()
self.__access_times.clear()
def has_key(self, key):
"""
This method should almost NEVER be used. The reason is that between the time
has_key is called, and the key is accessed, the key might vanish.
You should ALWAYS use a try: ... except KeyError: ... block.
>>> d = LRUCacheDict(max_size=3, expiration=1)
>>> d['foo'] = 'bar'
>>> d['foo']
'bar'
>>> import time
>>> if d.has_key('foo'):
... time.sleep(2) #Oops, the key 'foo' is gone!
... d['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
"""
return self.__values.has_key(key)
def __setitem__(self, key, value):
t = int(time())
self.__delete__(key)
self.__values[key] = value
self.__access_times[key] = t
self.__expire_times[key] = t + self.expiration
self.cleanup()
def __getitem__(self, key):
t = int(time())
del self.__access_times[key]
self.__access_times[key] = t
self.cleanup()
return self.__values[key]
def __delete__(self, key):
if self.__values.has_key(key):
del self.__values[key]
del self.__expire_times[key]
del self.__access_times[key]
def cleanup(self):
if self.expiration is None:
return None
t = int(time())
#Delete expired
for k in self.__expire_times.iterkeys():
if self.__expire_times[k] < t:
self.__delete__(k)
else:
break
#If we have more than self.max_size items, delete the oldest
while (len(self.__values) > self.max_size):
for k in self.__access_times.iterkeys():
self.__delete__(k)
break
class LRUCachedFunction(object):
"""
A memoized function, backed by an LRU cache.
>>> def f(x):
... print "Calling f(" + str(x) + ")"
... return x
>>> f = LRUCachedFunction(f, LRUCacheDict(max_size=3, expiration=3) )
>>> f(3)
Calling f(3)
3
>>> f(3)
3
>>> import time
>>> time.sleep(4) #Cache should now be empty, since expiration time is 3.
>>> f(3)
Calling f(3)
3
>>> f(4)
Calling f(4)
4
>>> f(5)
Calling f(5)
5
>>> f(3) #Still in cache, so no print statement. At this point, 4 is the least recently used.
3
>>> f(6)
Calling f(6)
6
>>> f(4) #No longer in cache - 4 is the least recently used, and there are at least 3 others items in cache [3,4,5,6].
Calling f(4)
4
"""
def __init__(self, function, cache=None):
if cache:
self.cache = cache
else:
self.cache = LRUCacheDict()
self.function = function
self.__name__ = self.function.__name__
def __call__(self, *args, **kwargs):
key = repr( (args, kwargs) ) + "#" + self.__name__ #In principle a python repr(...) should not return any # characters.
try:
return self.cache[key]
except KeyError:
value = self.function(*args, **kwargs)
self.cache[key] = value
return value
if __name__ == "__main__":
import doctest
doctest.testmod()