28
26
class _LRUNode(object):
29
27
"""This maintains the linked-list which is the lru internals."""
31
__slots__ = ('prev', 'next_key', 'key', 'value')
29
__slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
33
def __init__(self, key, value):
31
def __init__(self, key, value, cleanup=None):
35
33
self.next_key = _null_key
36
self.cleanup = cleanup
37
# TODO: We could compute this 'on-the-fly' like we used to, and remove
38
# one pointer from this object, we just need to decide if it
39
# actually costs us much of anything in normal usage
39
42
def __repr__(self):
40
43
if self.prev is None:
44
47
return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
45
48
self.next_key, prev_key)
50
def run_cleanup(self):
52
if self.cleanup is not None:
53
self.cleanup(self.key, self.value)
55
# cleanup might raise an exception, but we want to make sure
56
# to break refcycles, etc
48
61
class LRUCache(object):
49
62
"""A class which manages a cache of entries, removing unused ones."""
51
def __init__(self, max_cache=100, after_cleanup_count=None):
64
def __init__(self, max_cache=100, after_cleanup_count=None,
65
after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
66
if symbol_versioning.deprecated_passed(after_cleanup_size):
67
symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
68
' deprecated in 1.11. Use'
69
' after_cleanup_count instead.',
71
after_cleanup_count = after_cleanup_size
53
73
# The "HEAD" of the lru linked list
54
74
self._most_recently_used = None
93
113
def __len__(self):
94
114
return len(self._cache)
96
@symbol_versioning.deprecated_method(
97
symbol_versioning.deprecated_in((2, 5, 0)))
117
"""Walk the LRU list, only meant to be used in tests."""
118
node = self._most_recently_used
120
if node.prev is not None:
121
raise AssertionError('the _most_recently_used entry is not'
122
' supposed to have a previous entry'
124
while node is not None:
125
if node.next_key is _null_key:
126
if node is not self._least_recently_used:
127
raise AssertionError('only the last node should have'
128
' no next value: %s' % (node,))
131
node_next = self._cache[node.next_key]
132
if node_next.prev is not node:
133
raise AssertionError('inconsistency found, node.next.prev'
134
' != node: %s' % (node,))
135
if node.prev is None:
136
if node is not self._most_recently_used:
137
raise AssertionError('only the _most_recently_used should'
138
' not have a previous node: %s'
141
if node.prev.next_key != node.key:
142
raise AssertionError('inconsistency found, node.prev.next'
143
' != node: %s' % (node,))
98
147
def add(self, key, value, cleanup=None):
99
if cleanup is not None:
100
raise ValueError("Per-node cleanup functions no longer supported")
101
return self.__setitem__(key, value)
103
def __setitem__(self, key, value):
104
"""Add a new value to the cache"""
148
"""Add a new value to the cache.
150
Also, if the entry is ever removed from the cache, call
153
:param key: The key to store it under
154
:param value: The object to store
155
:param cleanup: None or a function taking (key, value) to indicate
156
'value' should be cleaned up.
105
158
if key is _null_key:
106
159
raise ValueError('cannot use _null_key as a key')
107
160
if key in self._cache:
108
161
node = self._cache[key]
110
self._record_access(node)
165
# Maintain the LRU properties, even if cleanup raises an
168
node.cleanup = cleanup
169
self._record_access(node)
112
node = _LRUNode(key, value)
171
node = _LRUNode(key, value, cleanup=cleanup)
113
172
self._cache[key] = node
114
173
self._record_access(node)
140
199
return self._cache.keys()
143
"""Get a new dict with the same key:value pairs as the cache"""
202
"""Get the key:value pairs as a dict."""
144
203
return dict((k, n.value) for k, n in self._cache.iteritems())
146
items = symbol_versioning.deprecated_method(
147
symbol_versioning.deprecated_in((2, 5, 0)))(as_dict)
149
205
def cleanup(self):
150
206
"""Clear the cache until it shrinks to the requested size.
156
212
while len(self._cache) > self._after_cleanup_count:
157
213
self._remove_lru()
215
def __setitem__(self, key, value):
216
"""Add a value to the cache, there will be no cleanup function."""
217
self.add(key, value, cleanup=None)
159
219
def _record_access(self, node):
160
220
"""Record that key was accessed."""
161
221
# Move 'node' to the front of the queue
189
249
# If we have removed all entries, remove the head pointer as well
190
250
if self._least_recently_used is None:
191
251
self._most_recently_used = None
192
if node.prev is not None:
193
node.prev.next_key = node.next_key
194
if node.next_key is not _null_key:
195
node_next = self._cache[node.next_key]
196
node_next.prev = node.prev
197
# And remove this node's pointers
199
node.next_key = _null_key
255
# cleanup might raise an exception, but we want to make sure to
256
# maintain the linked list
257
if node.prev is not None:
258
node.prev.next_key = node.next_key
259
if node.next_key is not _null_key:
260
node_next = self._cache[node.next_key]
261
node_next.prev = node.prev
262
# And remove this node's pointers
264
node.next_key = _null_key
201
266
def _remove_lru(self):
202
267
"""Remove one entry from the lru, and handle consequences.
259
324
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
260
325
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
262
def __setitem__(self, key, value):
263
"""Add a new value to the cache"""
327
def add(self, key, value, cleanup=None):
328
"""Add a new value to the cache.
330
Also, if the entry is ever removed from the cache, call
333
:param key: The key to store it under
334
:param value: The object to store
335
:param cleanup: None or a function taking (key, value) to indicate
336
'value' should be cleaned up.
264
338
if key is _null_key:
265
339
raise ValueError('cannot use _null_key as a key')
266
340
node = self._cache.get(key, None)
275
349
if node is not None:
276
350
# We won't be replacing the old node, so just remove it
277
351
self._remove_node(node)
352
if cleanup is not None:
280
node = _LRUNode(key, value)
356
node = _LRUNode(key, value, cleanup=cleanup)
281
357
self._cache[key] = node
283
self._value_size -= self._compute_size(node.value)
359
self._value_size -= node.size
360
node.size = value_len
284
361
self._value_size += value_len
285
362
self._record_access(node)
299
376
self._remove_lru()
301
378
def _remove_node(self, node):
302
self._value_size -= self._compute_size(node.value)
379
self._value_size -= node.size
303
380
LRUCache._remove_node(self, node)
305
382
def resize(self, max_size, after_cleanup_size=None):