Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 1 | """functools.py - Tools for working with functions and callable objects |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 2 | """ |
| 3 | # Python module wrapper for _functools C module |
| 4 | # to allow utilities written in Python to be added |
| 5 | # to the functools module. |
| 6 | # Written by Nick Coghlan <ncoghlan at gmail.com> |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 7 | # and Raymond Hettinger <python at rcn.com> |
| 8 | # Copyright (C) 2006-2010 Python Software Foundation. |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 9 | # See C source code for _functools credits/copyright |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 10 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 11 | __all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', |
Benjamin Peterson | 1017ae5 | 2010-09-10 23:35:52 +0000 | [diff] [blame] | 12 | 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial'] |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 13 | |
Guido van Rossum | 0919a1a | 2006-08-26 20:49:04 +0000 | [diff] [blame] | 14 | from _functools import partial, reduce |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 15 | from collections import namedtuple |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 16 | try: |
Raymond Hettinger | fd54117 | 2013-03-01 03:47:57 -0800 | [diff] [blame] | 17 | from _thread import RLock |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 18 | except: |
Raymond Hettinger | 409f663 | 2013-03-01 23:20:13 -0800 | [diff] [blame] | 19 | class RLock: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 20 | 'Dummy reentrant lock for builds without threads' |
Raymond Hettinger | 409f663 | 2013-03-01 23:20:13 -0800 | [diff] [blame] | 21 | def __enter__(self): pass |
| 22 | def __exit__(self, exctype, excinst, exctb): pass |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 23 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 24 | |
| 25 | ################################################################################ |
| 26 | ### update_wrapper() and wraps() decorator |
| 27 | ################################################################################ |
| 28 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 29 | # update_wrapper() and wraps() are tools to help write |
| 30 | # wrapper functions that can handle naive introspection |
| 31 | |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 32 | WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__', |
| 33 | '__annotations__') |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 34 | WRAPPER_UPDATES = ('__dict__',) |
| 35 | def update_wrapper(wrapper, |
| 36 | wrapped, |
| 37 | assigned = WRAPPER_ASSIGNMENTS, |
| 38 | updated = WRAPPER_UPDATES): |
| 39 | """Update a wrapper function to look like the wrapped function |
| 40 | |
| 41 | wrapper is the function to be updated |
| 42 | wrapped is the original function |
| 43 | assigned is a tuple naming the attributes assigned directly |
| 44 | from the wrapped function to the wrapper function (defaults to |
| 45 | functools.WRAPPER_ASSIGNMENTS) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 46 | updated is a tuple naming the attributes of the wrapper that |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 47 | are updated with the corresponding attribute from the wrapped |
| 48 | function (defaults to functools.WRAPPER_UPDATES) |
| 49 | """ |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 50 | wrapper.__wrapped__ = wrapped |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 51 | for attr in assigned: |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 52 | try: |
| 53 | value = getattr(wrapped, attr) |
| 54 | except AttributeError: |
| 55 | pass |
| 56 | else: |
| 57 | setattr(wrapper, attr, value) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 58 | for attr in updated: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 59 | getattr(wrapper, attr).update(getattr(wrapped, attr, {})) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 60 | # Return the wrapper so this can be used as a decorator via partial() |
| 61 | return wrapper |
| 62 | |
| 63 | def wraps(wrapped, |
| 64 | assigned = WRAPPER_ASSIGNMENTS, |
| 65 | updated = WRAPPER_UPDATES): |
| 66 | """Decorator factory to apply update_wrapper() to a wrapper function |
| 67 | |
| 68 | Returns a decorator that invokes update_wrapper() with the decorated |
| 69 | function as the wrapper argument and the arguments to wraps() as the |
| 70 | remaining arguments. Default arguments are as for update_wrapper(). |
| 71 | This is a convenience function to simplify applying partial() to |
| 72 | update_wrapper(). |
| 73 | """ |
| 74 | return partial(update_wrapper, wrapped=wrapped, |
| 75 | assigned=assigned, updated=updated) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 76 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 77 | |
| 78 | ################################################################################ |
| 79 | ### total_ordering class decorator |
| 80 | ################################################################################ |
| 81 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 82 | def total_ordering(cls): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 83 | """Class decorator that fills in missing ordering methods""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 84 | convert = { |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 85 | '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), |
| 86 | ('__le__', lambda self, other: self < other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 87 | ('__ge__', lambda self, other: not self < other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 88 | '__le__': [('__ge__', lambda self, other: not self <= other or self == other), |
| 89 | ('__lt__', lambda self, other: self <= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 90 | ('__gt__', lambda self, other: not self <= other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 91 | '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), |
| 92 | ('__ge__', lambda self, other: self > other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 93 | ('__le__', lambda self, other: not self > other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 94 | '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), |
| 95 | ('__gt__', lambda self, other: self >= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 96 | ('__lt__', lambda self, other: not self >= other)] |
| 97 | } |
Raymond Hettinger | 3255c63 | 2010-09-16 00:31:21 +0000 | [diff] [blame] | 98 | # Find user-defined comparisons (not those inherited from object). |
Raymond Hettinger | 1006bd4 | 2010-09-14 22:55:13 +0000 | [diff] [blame] | 99 | roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)] |
Raymond Hettinger | 56de7e2 | 2010-04-10 16:59:03 +0000 | [diff] [blame] | 100 | if not roots: |
| 101 | raise ValueError('must define at least one ordering operation: < > <= >=') |
| 102 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 103 | for opname, opfunc in convert[root]: |
| 104 | if opname not in roots: |
| 105 | opfunc.__name__ = opname |
| 106 | opfunc.__doc__ = getattr(int, opname).__doc__ |
| 107 | setattr(cls, opname, opfunc) |
| 108 | return cls |
| 109 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 110 | |
| 111 | ################################################################################ |
| 112 | ### cmp_to_key() function converter |
| 113 | ################################################################################ |
| 114 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 115 | def cmp_to_key(mycmp): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 116 | """Convert a cmp= function into a key= function""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 117 | class K(object): |
Raymond Hettinger | a0d1d96 | 2011-03-21 17:50:28 -0700 | [diff] [blame] | 118 | __slots__ = ['obj'] |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 119 | def __init__(self, obj): |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 120 | self.obj = obj |
| 121 | def __lt__(self, other): |
| 122 | return mycmp(self.obj, other.obj) < 0 |
| 123 | def __gt__(self, other): |
| 124 | return mycmp(self.obj, other.obj) > 0 |
| 125 | def __eq__(self, other): |
| 126 | return mycmp(self.obj, other.obj) == 0 |
| 127 | def __le__(self, other): |
| 128 | return mycmp(self.obj, other.obj) <= 0 |
| 129 | def __ge__(self, other): |
| 130 | return mycmp(self.obj, other.obj) >= 0 |
| 131 | def __ne__(self, other): |
| 132 | return mycmp(self.obj, other.obj) != 0 |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 133 | __hash__ = None |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 134 | return K |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 135 | |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 136 | try: |
| 137 | from _functools import cmp_to_key |
| 138 | except ImportError: |
| 139 | pass |
| 140 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 141 | |
| 142 | ################################################################################ |
| 143 | ### LRU Cache function decorator |
| 144 | ################################################################################ |
| 145 | |
Raymond Hettinger | dce583e | 2012-03-16 22:12:20 -0700 | [diff] [blame] | 146 | _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 147 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 148 | class _HashedSeq(list): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 149 | """ This class guarantees that hash() will be called no more than once |
| 150 | per element. This is important because the lru_cache() will hash |
| 151 | the key multiple times on a cache miss. |
| 152 | |
| 153 | """ |
| 154 | |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 155 | __slots__ = 'hashvalue' |
| 156 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 157 | def __init__(self, tup, hash=hash): |
| 158 | self[:] = tup |
| 159 | self.hashvalue = hash(tup) |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 160 | |
| 161 | def __hash__(self): |
| 162 | return self.hashvalue |
| 163 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 164 | def _make_key(args, kwds, typed, |
| 165 | kwd_mark = (object(),), |
| 166 | fasttypes = {int, str, frozenset, type(None)}, |
| 167 | sorted=sorted, tuple=tuple, type=type, len=len): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 168 | """Make a cache key from optionally typed positional and keyword arguments |
| 169 | |
| 170 | The key is constructed in a way that is flat as possible rather than |
| 171 | as a nested structure that would take more memory. |
| 172 | |
| 173 | If there is only a single argument and its data type is known to cache |
| 174 | its hash value, then that argument is returned without a wrapper. This |
| 175 | saves space and improves lookup speed. |
| 176 | |
| 177 | """ |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 178 | key = args |
| 179 | if kwds: |
| 180 | sorted_items = sorted(kwds.items()) |
| 181 | key += kwd_mark |
| 182 | for item in sorted_items: |
| 183 | key += item |
| 184 | if typed: |
| 185 | key += tuple(type(v) for v in args) |
| 186 | if kwds: |
| 187 | key += tuple(type(v) for k, v in sorted_items) |
| 188 | elif len(key) == 1 and type(key[0]) in fasttypes: |
| 189 | return key[0] |
| 190 | return _HashedSeq(key) |
| 191 | |
Raymond Hettinger | 010ce32 | 2012-05-19 21:20:48 -0700 | [diff] [blame] | 192 | def lru_cache(maxsize=128, typed=False): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 193 | """Least-recently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 194 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 195 | If *maxsize* is set to None, the LRU features are disabled and the cache |
| 196 | can grow without bound. |
| 197 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 198 | If *typed* is True, arguments of different types will be cached separately. |
| 199 | For example, f(3.0) and f(3) will be treated as distinct calls with |
| 200 | distinct results. |
| 201 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 202 | Arguments to the cached function must be hashable. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 203 | |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 204 | View the cache statistics named tuple (hits, misses, maxsize, currsize) |
| 205 | with f.cache_info(). Clear the cache and statistics with f.cache_clear(). |
Raymond Hettinger | 00f2f97 | 2010-12-01 00:47:56 +0000 | [diff] [blame] | 206 | Access the underlying function with f.__wrapped__. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 207 | |
| 208 | See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 209 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 210 | """ |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 211 | |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 212 | # Users should only access the lru_cache through its public API: |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 213 | # cache_info, cache_clear, and f.__wrapped__ |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 214 | # The internals of the lru_cache are encapsulated for thread safety and |
| 215 | # to allow the implementation to change (including a possible C version). |
| 216 | |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 217 | # Constants shared by all lru cache instances: |
Raymond Hettinger | b6b98c0 | 2012-04-29 18:09:02 -0700 | [diff] [blame] | 218 | sentinel = object() # unique object used to signal cache misses |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 219 | make_key = _make_key # build a key from the function arguments |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 220 | PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields |
| 221 | |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 222 | def decorating_function(user_function): |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 223 | |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 224 | cache = {} |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 225 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 226 | full = False |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 227 | cache_get = cache.get # bound method to lookup a key or return None |
Raymond Hettinger | fd54117 | 2013-03-01 03:47:57 -0800 | [diff] [blame] | 228 | lock = RLock() # because linkedlist updates aren't threadsafe |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 229 | root = [] # root of the circular doubly linked list |
| 230 | root[:] = [root, root, None, None] # initialize by pointing to self |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 231 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 232 | if maxsize == 0: |
| 233 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 234 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 235 | # No caching -- just a statistics update after a successful call |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 236 | nonlocal misses |
Raymond Hettinger | 7dabfed | 2012-03-17 15:11:09 -0700 | [diff] [blame] | 237 | result = user_function(*args, **kwds) |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 238 | misses += 1 |
| 239 | return result |
| 240 | |
| 241 | elif maxsize is None: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 242 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 243 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 244 | # Simple caching without ordering or size limit |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 245 | nonlocal hits, misses |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 246 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 247 | result = cache_get(key, sentinel) |
| 248 | if result is not sentinel: |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 249 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 250 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 251 | result = user_function(*args, **kwds) |
| 252 | cache[key] = result |
| 253 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 254 | return result |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 255 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 256 | else: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 257 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 258 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 259 | # Size limited caching that tracks accesses by recency |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 260 | nonlocal root, hits, misses, full |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 261 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 262 | with lock: |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 263 | link = cache_get(key) |
| 264 | if link is not None: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 265 | # Move the link to the front of the circular queue |
| 266 | link_prev, link_next, _key, result = link |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 267 | link_prev[NEXT] = link_next |
| 268 | link_next[PREV] = link_prev |
| 269 | last = root[PREV] |
| 270 | last[NEXT] = root[PREV] = link |
| 271 | link[PREV] = last |
| 272 | link[NEXT] = root |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 273 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 274 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 275 | result = user_function(*args, **kwds) |
| 276 | with lock: |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 277 | if key in cache: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 278 | # Getting here means that this same key was added to the |
| 279 | # cache while the lock was released. Since the link |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 280 | # update is already done, we need only return the |
| 281 | # computed result and update the count of misses. |
| 282 | pass |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 283 | elif full: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 284 | # Use the old root to store the new key and result. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 285 | oldroot = root |
| 286 | oldroot[KEY] = key |
| 287 | oldroot[RESULT] = result |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 288 | # Empty the oldest link and make it the new root. |
| 289 | # Keep a reference to the old key and old result to |
| 290 | # prevent their ref counts from going to zero during the |
| 291 | # update. That will prevent potentially arbitrary object |
| 292 | # clean-up code (i.e. __del__) from running while we're |
| 293 | # still adjusting the links. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 294 | root = oldroot[NEXT] |
| 295 | oldkey = root[KEY] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 296 | oldresult = root[RESULT] |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 297 | root[KEY] = root[RESULT] = None |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 298 | # Now update the cache dictionary. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 299 | del cache[oldkey] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 300 | # Save the potentially reentrant cache[key] assignment |
| 301 | # for last, after the root and links have been put in |
| 302 | # a consistent state. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 303 | cache[key] = oldroot |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 304 | else: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 305 | # Put result in a new link at the front of the queue. |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 306 | last = root[PREV] |
| 307 | link = [last, root, key, result] |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 308 | last[NEXT] = root[PREV] = cache[key] = link |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 309 | full = (len(cache) >= maxsize) |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 310 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 311 | return result |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 312 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 313 | def cache_info(): |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 314 | """Report cache statistics""" |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 315 | with lock: |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 316 | return _CacheInfo(hits, misses, maxsize, len(cache)) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 317 | |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 318 | def cache_clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 319 | """Clear the cache and cache statistics""" |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 320 | nonlocal hits, misses, full |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 321 | with lock: |
| 322 | cache.clear() |
Benjamin Peterson | 954cf57 | 2012-03-16 18:22:26 -0500 | [diff] [blame] | 323 | root[:] = [root, root, None, None] |
Raymond Hettinger | d8d6010 | 2013-03-08 23:01:07 -0800 | [diff] [blame] | 324 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 325 | full = False |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 326 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 327 | wrapper.cache_info = cache_info |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 328 | wrapper.cache_clear = cache_clear |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 329 | return update_wrapper(wrapper, user_function) |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 330 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 331 | return decorating_function |