aboutsummaryrefslogtreecommitdiff
path: root/cachetools.py
blob: ccc42f9ec8b02d7e54f347896907a00701d8b610 (plain)
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""Extensible memoizing collections and decorators"""

import collections
import functools
import operator
import random

try:
    from threading import RLock
except ImportError:
    from dummy_threading import RLock

__version__ = '0.3.1'


class _Cache(collections.MutableMapping):
    """Class that wraps a mutable mapping to work as a cache."""

    def __init__(self, mapping, maxsize):
        self.__data = mapping
        self.__size = sum(map(self.getsizeof, mapping.values()), 0)
        self.maxsize = maxsize

    def __getitem__(self, key):
        return self.__data[key]

    def __setitem__(self, key, value):
        size = self.getsizeof(value)
        if size > self.maxsize:
            raise ValueError
        while self.size > self.maxsize - size:
            self.pop(next(iter(self)))
        self.__data[key] = value
        self.__size += size

    def __delitem__(self, key):
        self.__size -= self.getsizeof(self.__data.pop(key))

    def __iter__(self):
        return iter(self.__data)

    def __len__(self):
        return len(self.__data)

    def __repr__(self):
        return '%s(%r, size=%d, maxsize=%d)' % (
            self.__class__.__name__,
            self.__data,
            self.__size,
            self.__maxsize,
        )

    @property
    def size(self):
        return self.__size

    @property
    def maxsize(self):
        return self.__maxsize

    @maxsize.setter
    def maxsize(self, value):
        while self.size > value:
            self.pop(next(iter(self)))
        self.__maxsize = value

    @staticmethod
    def getsizeof(_):
        return 1


class LRUCache(_Cache):
    """Least Recently Used (LRU) cache implementation.

    Discards the least recently used items first to make space when
    necessary.

    This implementation uses :class:`collections.OrderedDict` to keep
    track of item usage.
    """

    class OrderedDict(collections.OrderedDict):
        # OrderedDict.move_to_end is only available in Python 3
        if hasattr(collections.OrderedDict, 'move_to_end'):
            def __getitem__(self, key,
                            getitem=collections.OrderedDict.__getitem__):
                self.move_to_end(key)
                return getitem(self, key)
        else:
            def __getitem__(self, key,
                            getitem=collections.OrderedDict.__getitem__,
                            delitem=collections.OrderedDict.__delitem__,
                            setitem=collections.OrderedDict.__setitem__):
                value = getitem(self, key)
                delitem(self, key)
                setitem(self, key, value)
                return value

    def __init__(self, maxsize, getsizeof=None):
        if getsizeof is not None:
            self.getsizeof = getsizeof
        _Cache.__init__(self, self.OrderedDict(), maxsize)


class LFUCache(_Cache):
    """Least Frequently Used (LFU) cache implementation.

    Counts how often an item is needed, and discards the items used
    least often to make space when necessary.

    This implementation uses :class:`collections.Counter` to keep
    track of usage counts.
    """

    def __init__(self, maxsize, getsizeof=None):
        if getsizeof is not None:
            self.getsizeof = getsizeof
        _Cache.__init__(self, {}, maxsize)
        self.__counter = collections.Counter()

    def __getitem__(self, key):
        value = _Cache.__getitem__(self, key)
        self.__counter[key] += 1
        return value

    def __setitem__(self, key, value):
        _Cache.__setitem__(self, key, value)
        self.__counter[key] += 0

    def __delitem__(self, key):
        _Cache.__delitem__(self, key)
        del self.__counter[key]

    def __iter__(self):
        items = reversed(self.__counter.most_common())
        return iter(map(operator.itemgetter(0), items))


class RRCache(_Cache):
    """Random Replacement (RR) cache implementation.

    Randomly selects candidate items and discards then to make space
    when necessary.

    This implementations uses :func:`random.shuffle` to select the
    items to be discarded.
    """

    def __init__(self, maxsize, getsizeof=None):
        if getsizeof is not None:
            self.getsizeof = getsizeof
        _Cache.__init__(self, {}, maxsize)

    def __iter__(self):
        keys = list(_Cache.__iter__(self))
        random.shuffle(keys)
        return iter(keys)


CacheInfo = collections.namedtuple('CacheInfo', 'hits misses maxsize currsize')


def _makekey(args, kwargs):
    return (args, tuple(sorted(kwargs.items())))


def _makekey_typed(args, kwargs):
    key = _makekey(args, kwargs)
    key += tuple(type(v) for v in args)
    key += tuple(type(v) for k, v in sorted(kwargs.items()))
    return key


def _cachedfunc(cache, makekey, lock):
    def decorator(func):
        stats = [0, 0]

        def wrapper(*args, **kwargs):
            key = makekey(args, kwargs)
            with lock:
                try:
                    result = cache[key]
                    stats[0] += 1
                    return result
                except KeyError:
                    stats[1] += 1
            result = func(*args, **kwargs)
            with lock:
                cache[key] = result
            return result

        def cache_info():
            with lock:
                return CacheInfo(stats[0], stats[1], cache.maxsize, cache.size)

        def cache_clear():
            with lock:
                cache.clear()

        wrapper.cache_info = cache_info
        wrapper.cache_clear = cache_clear
        return functools.update_wrapper(wrapper, func)

    return decorator


def _cachedmeth(getcache, makekey, lock):
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            key = makekey((func,) + args, kwargs)
            cache = getcache(self)
            with lock:
                try:
                    return cache[key]
                except KeyError:
                    pass
            result = func(self, *args, **kwargs)
            with lock:
                cache[key] = result
            return result

        return functools.update_wrapper(wrapper, func)

    return decorator


def lru_cache(maxsize=128, typed=False, getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Least Recently Used (LRU)
    algorithm.

    """
    makekey = _makekey_typed if typed else _makekey
    return _cachedfunc(LRUCache(maxsize, getsizeof), makekey, lock())


def lfu_cache(maxsize=128, typed=False, getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Least Frequently Used (LFU)
    algorithm.

    """
    makekey = _makekey_typed if typed else _makekey
    return _cachedfunc(LFUCache(maxsize, getsizeof), makekey, lock())


def rr_cache(maxsize=128, typed=False, getsizeof=None, lock=RLock):
    """Decorator to wrap a function with a memoizing callable that saves
    up to `maxsize` results based on a Random Replacement (RR)
    algorithm.

    """
    makekey = _makekey_typed if typed else _makekey
    return _cachedfunc(RRCache(maxsize, getsizeof), makekey, lock())


def cachedmethod(getcache, typed=False, lock=RLock):
    """Decorator to wrap a class or instance method with a memoizing
    callable that saves results in a (possibly shared) cache.

    """
    makekey = _makekey_typed if typed else _makekey
    return _cachedmeth(getcache, makekey, lock())