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