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. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame^] | 6 | # Written by Nick Coghlan <ncoghlan at gmail.com>, |
| 7 | # Raymond Hettinger <python at rcn.com>, |
| 8 | # and Łukasz Langa <lukasz at langa.pl>. |
| 9 | # Copyright (C) 2006-2013 Python Software Foundation. |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 10 | # See C source code for _functools credits/copyright |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 11 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 12 | __all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame^] | 13 | 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial', |
| 14 | 'singledispatch'] |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 15 | |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 16 | try: |
| 17 | from _functools import reduce |
| 18 | except ImportError: |
| 19 | pass |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame^] | 20 | from abc import get_cache_token |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 21 | from collections import namedtuple |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame^] | 22 | from types import MappingProxyType |
| 23 | from weakref import WeakKeyDictionary |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 24 | try: |
Raymond Hettinger | fd54117 | 2013-03-01 03:47:57 -0800 | [diff] [blame] | 25 | from _thread import RLock |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 26 | except: |
Raymond Hettinger | 409f663 | 2013-03-01 23:20:13 -0800 | [diff] [blame] | 27 | class RLock: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 28 | 'Dummy reentrant lock for builds without threads' |
Raymond Hettinger | 409f663 | 2013-03-01 23:20:13 -0800 | [diff] [blame] | 29 | def __enter__(self): pass |
| 30 | def __exit__(self, exctype, excinst, exctb): pass |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 31 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 32 | |
| 33 | ################################################################################ |
| 34 | ### update_wrapper() and wraps() decorator |
| 35 | ################################################################################ |
| 36 | |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 37 | # update_wrapper() and wraps() are tools to help write |
| 38 | # wrapper functions that can handle naive introspection |
| 39 | |
Meador Inge | ff7f64c | 2011-12-11 22:37:31 -0600 | [diff] [blame] | 40 | WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__', |
| 41 | '__annotations__') |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 42 | WRAPPER_UPDATES = ('__dict__',) |
| 43 | def update_wrapper(wrapper, |
| 44 | wrapped, |
| 45 | assigned = WRAPPER_ASSIGNMENTS, |
| 46 | updated = WRAPPER_UPDATES): |
| 47 | """Update a wrapper function to look like the wrapped function |
| 48 | |
| 49 | wrapper is the function to be updated |
| 50 | wrapped is the original function |
| 51 | assigned is a tuple naming the attributes assigned directly |
| 52 | from the wrapped function to the wrapper function (defaults to |
| 53 | functools.WRAPPER_ASSIGNMENTS) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 54 | updated is a tuple naming the attributes of the wrapper that |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 55 | are updated with the corresponding attribute from the wrapped |
| 56 | function (defaults to functools.WRAPPER_UPDATES) |
| 57 | """ |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 58 | wrapper.__wrapped__ = wrapped |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 59 | for attr in assigned: |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 60 | try: |
| 61 | value = getattr(wrapped, attr) |
| 62 | except AttributeError: |
| 63 | pass |
| 64 | else: |
| 65 | setattr(wrapper, attr, value) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 66 | for attr in updated: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 67 | getattr(wrapper, attr).update(getattr(wrapped, attr, {})) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 68 | # Return the wrapper so this can be used as a decorator via partial() |
| 69 | return wrapper |
| 70 | |
| 71 | def wraps(wrapped, |
| 72 | assigned = WRAPPER_ASSIGNMENTS, |
| 73 | updated = WRAPPER_UPDATES): |
| 74 | """Decorator factory to apply update_wrapper() to a wrapper function |
| 75 | |
| 76 | Returns a decorator that invokes update_wrapper() with the decorated |
| 77 | function as the wrapper argument and the arguments to wraps() as the |
| 78 | remaining arguments. Default arguments are as for update_wrapper(). |
| 79 | This is a convenience function to simplify applying partial() to |
| 80 | update_wrapper(). |
| 81 | """ |
| 82 | return partial(update_wrapper, wrapped=wrapped, |
| 83 | assigned=assigned, updated=updated) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 84 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 85 | |
| 86 | ################################################################################ |
| 87 | ### total_ordering class decorator |
| 88 | ################################################################################ |
| 89 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 90 | def total_ordering(cls): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 91 | """Class decorator that fills in missing ordering methods""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 92 | convert = { |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 93 | '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), |
| 94 | ('__le__', lambda self, other: self < other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 95 | ('__ge__', lambda self, other: not self < other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 96 | '__le__': [('__ge__', lambda self, other: not self <= other or self == other), |
| 97 | ('__lt__', lambda self, other: self <= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 98 | ('__gt__', lambda self, other: not self <= other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 99 | '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)), |
| 100 | ('__ge__', lambda self, other: self > other or self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 101 | ('__le__', lambda self, other: not self > other)], |
Raymond Hettinger | 23f9fc3 | 2011-01-08 07:01:56 +0000 | [diff] [blame] | 102 | '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other), |
| 103 | ('__gt__', lambda self, other: self >= other and not self == other), |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 104 | ('__lt__', lambda self, other: not self >= other)] |
| 105 | } |
Raymond Hettinger | 3255c63 | 2010-09-16 00:31:21 +0000 | [diff] [blame] | 106 | # Find user-defined comparisons (not those inherited from object). |
Raymond Hettinger | 1006bd4 | 2010-09-14 22:55:13 +0000 | [diff] [blame] | 107 | 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] | 108 | if not roots: |
| 109 | raise ValueError('must define at least one ordering operation: < > <= >=') |
| 110 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 111 | for opname, opfunc in convert[root]: |
| 112 | if opname not in roots: |
| 113 | opfunc.__name__ = opname |
| 114 | opfunc.__doc__ = getattr(int, opname).__doc__ |
| 115 | setattr(cls, opname, opfunc) |
| 116 | return cls |
| 117 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 118 | |
| 119 | ################################################################################ |
| 120 | ### cmp_to_key() function converter |
| 121 | ################################################################################ |
| 122 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 123 | def cmp_to_key(mycmp): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 124 | """Convert a cmp= function into a key= function""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 125 | class K(object): |
Raymond Hettinger | a0d1d96 | 2011-03-21 17:50:28 -0700 | [diff] [blame] | 126 | __slots__ = ['obj'] |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 127 | def __init__(self, obj): |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 128 | self.obj = obj |
| 129 | def __lt__(self, other): |
| 130 | return mycmp(self.obj, other.obj) < 0 |
| 131 | def __gt__(self, other): |
| 132 | return mycmp(self.obj, other.obj) > 0 |
| 133 | def __eq__(self, other): |
| 134 | return mycmp(self.obj, other.obj) == 0 |
| 135 | def __le__(self, other): |
| 136 | return mycmp(self.obj, other.obj) <= 0 |
| 137 | def __ge__(self, other): |
| 138 | return mycmp(self.obj, other.obj) >= 0 |
| 139 | def __ne__(self, other): |
| 140 | return mycmp(self.obj, other.obj) != 0 |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 141 | __hash__ = None |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 142 | return K |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 143 | |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 144 | try: |
| 145 | from _functools import cmp_to_key |
| 146 | except ImportError: |
| 147 | pass |
| 148 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 149 | |
| 150 | ################################################################################ |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 151 | ### partial() argument application |
| 152 | ################################################################################ |
| 153 | |
| 154 | def partial(func, *args, **keywords): |
| 155 | """new function with partial application of the given arguments |
| 156 | and keywords. |
| 157 | """ |
| 158 | def newfunc(*fargs, **fkeywords): |
| 159 | newkeywords = keywords.copy() |
| 160 | newkeywords.update(fkeywords) |
| 161 | return func(*(args + fargs), **newkeywords) |
| 162 | newfunc.func = func |
| 163 | newfunc.args = args |
| 164 | newfunc.keywords = keywords |
| 165 | return newfunc |
| 166 | |
| 167 | try: |
| 168 | from _functools import partial |
| 169 | except ImportError: |
| 170 | pass |
| 171 | |
| 172 | |
| 173 | ################################################################################ |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 174 | ### LRU Cache function decorator |
| 175 | ################################################################################ |
| 176 | |
Raymond Hettinger | dce583e | 2012-03-16 22:12:20 -0700 | [diff] [blame] | 177 | _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 178 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 179 | class _HashedSeq(list): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 180 | """ This class guarantees that hash() will be called no more than once |
| 181 | per element. This is important because the lru_cache() will hash |
| 182 | the key multiple times on a cache miss. |
| 183 | |
| 184 | """ |
| 185 | |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 186 | __slots__ = 'hashvalue' |
| 187 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 188 | def __init__(self, tup, hash=hash): |
| 189 | self[:] = tup |
| 190 | self.hashvalue = hash(tup) |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 191 | |
| 192 | def __hash__(self): |
| 193 | return self.hashvalue |
| 194 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 195 | def _make_key(args, kwds, typed, |
| 196 | kwd_mark = (object(),), |
| 197 | fasttypes = {int, str, frozenset, type(None)}, |
| 198 | sorted=sorted, tuple=tuple, type=type, len=len): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 199 | """Make a cache key from optionally typed positional and keyword arguments |
| 200 | |
| 201 | The key is constructed in a way that is flat as possible rather than |
| 202 | as a nested structure that would take more memory. |
| 203 | |
| 204 | If there is only a single argument and its data type is known to cache |
| 205 | its hash value, then that argument is returned without a wrapper. This |
| 206 | saves space and improves lookup speed. |
| 207 | |
| 208 | """ |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 209 | key = args |
| 210 | if kwds: |
| 211 | sorted_items = sorted(kwds.items()) |
| 212 | key += kwd_mark |
| 213 | for item in sorted_items: |
| 214 | key += item |
| 215 | if typed: |
| 216 | key += tuple(type(v) for v in args) |
| 217 | if kwds: |
| 218 | key += tuple(type(v) for k, v in sorted_items) |
| 219 | elif len(key) == 1 and type(key[0]) in fasttypes: |
| 220 | return key[0] |
| 221 | return _HashedSeq(key) |
| 222 | |
Raymond Hettinger | 010ce32 | 2012-05-19 21:20:48 -0700 | [diff] [blame] | 223 | def lru_cache(maxsize=128, typed=False): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 224 | """Least-recently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 225 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 226 | If *maxsize* is set to None, the LRU features are disabled and the cache |
| 227 | can grow without bound. |
| 228 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 229 | If *typed* is True, arguments of different types will be cached separately. |
| 230 | For example, f(3.0) and f(3) will be treated as distinct calls with |
| 231 | distinct results. |
| 232 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 233 | Arguments to the cached function must be hashable. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 234 | |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 235 | View the cache statistics named tuple (hits, misses, maxsize, currsize) |
| 236 | 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] | 237 | Access the underlying function with f.__wrapped__. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 238 | |
| 239 | See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 240 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 241 | """ |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 242 | |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 243 | # Users should only access the lru_cache through its public API: |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 244 | # cache_info, cache_clear, and f.__wrapped__ |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 245 | # The internals of the lru_cache are encapsulated for thread safety and |
| 246 | # to allow the implementation to change (including a possible C version). |
| 247 | |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 248 | # Constants shared by all lru cache instances: |
Raymond Hettinger | b6b98c0 | 2012-04-29 18:09:02 -0700 | [diff] [blame] | 249 | sentinel = object() # unique object used to signal cache misses |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 250 | make_key = _make_key # build a key from the function arguments |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 251 | PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields |
| 252 | |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 253 | def decorating_function(user_function): |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 254 | cache = {} |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 255 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 256 | full = False |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 257 | 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] | 258 | lock = RLock() # because linkedlist updates aren't threadsafe |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 259 | root = [] # root of the circular doubly linked list |
| 260 | root[:] = [root, root, None, None] # initialize by pointing to self |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 261 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 262 | if maxsize == 0: |
| 263 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 264 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 265 | # No caching -- just a statistics update after a successful call |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 266 | nonlocal misses |
Raymond Hettinger | 7dabfed | 2012-03-17 15:11:09 -0700 | [diff] [blame] | 267 | result = user_function(*args, **kwds) |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 268 | misses += 1 |
| 269 | return result |
| 270 | |
| 271 | elif maxsize is None: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 272 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 273 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 274 | # Simple caching without ordering or size limit |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 275 | nonlocal hits, misses |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 276 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 277 | result = cache_get(key, sentinel) |
| 278 | if result is not sentinel: |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 279 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 280 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 281 | result = user_function(*args, **kwds) |
| 282 | cache[key] = result |
| 283 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 284 | return result |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 285 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 286 | else: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 287 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 288 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 289 | # Size limited caching that tracks accesses by recency |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 290 | nonlocal root, hits, misses, full |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 291 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 292 | with lock: |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 293 | link = cache_get(key) |
| 294 | if link is not None: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 295 | # Move the link to the front of the circular queue |
| 296 | link_prev, link_next, _key, result = link |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 297 | link_prev[NEXT] = link_next |
| 298 | link_next[PREV] = link_prev |
| 299 | last = root[PREV] |
| 300 | last[NEXT] = root[PREV] = link |
| 301 | link[PREV] = last |
| 302 | link[NEXT] = root |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 303 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 304 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 305 | result = user_function(*args, **kwds) |
| 306 | with lock: |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 307 | if key in cache: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 308 | # Getting here means that this same key was added to the |
| 309 | # cache while the lock was released. Since the link |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 310 | # update is already done, we need only return the |
| 311 | # computed result and update the count of misses. |
| 312 | pass |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 313 | elif full: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 314 | # Use the old root to store the new key and result. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 315 | oldroot = root |
| 316 | oldroot[KEY] = key |
| 317 | oldroot[RESULT] = result |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 318 | # Empty the oldest link and make it the new root. |
| 319 | # Keep a reference to the old key and old result to |
| 320 | # prevent their ref counts from going to zero during the |
| 321 | # update. That will prevent potentially arbitrary object |
| 322 | # clean-up code (i.e. __del__) from running while we're |
| 323 | # still adjusting the links. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 324 | root = oldroot[NEXT] |
| 325 | oldkey = root[KEY] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 326 | oldresult = root[RESULT] |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 327 | root[KEY] = root[RESULT] = None |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 328 | # Now update the cache dictionary. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 329 | del cache[oldkey] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 330 | # Save the potentially reentrant cache[key] assignment |
| 331 | # for last, after the root and links have been put in |
| 332 | # a consistent state. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 333 | cache[key] = oldroot |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 334 | else: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 335 | # Put result in a new link at the front of the queue. |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 336 | last = root[PREV] |
| 337 | link = [last, root, key, result] |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 338 | last[NEXT] = root[PREV] = cache[key] = link |
Raymond Hettinger | bb5f480 | 2013-03-04 04:20:46 -0500 | [diff] [blame] | 339 | full = (len(cache) >= maxsize) |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 340 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 341 | return result |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 342 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 343 | def cache_info(): |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 344 | """Report cache statistics""" |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 345 | with lock: |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 346 | return _CacheInfo(hits, misses, maxsize, len(cache)) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 347 | |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 348 | def cache_clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 349 | """Clear the cache and cache statistics""" |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 350 | nonlocal hits, misses, full |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 351 | with lock: |
| 352 | cache.clear() |
Benjamin Peterson | 954cf57 | 2012-03-16 18:22:26 -0500 | [diff] [blame] | 353 | root[:] = [root, root, None, None] |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 354 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 355 | full = False |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 356 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 357 | wrapper.cache_info = cache_info |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 358 | wrapper.cache_clear = cache_clear |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 359 | return update_wrapper(wrapper, user_function) |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 360 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 361 | return decorating_function |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame^] | 362 | |
| 363 | |
| 364 | ################################################################################ |
| 365 | ### singledispatch() - single-dispatch generic function decorator |
| 366 | ################################################################################ |
| 367 | |
| 368 | def _compose_mro(cls, haystack): |
| 369 | """Calculates the MRO for a given class `cls`, including relevant abstract |
| 370 | base classes from `haystack`. |
| 371 | |
| 372 | """ |
| 373 | bases = set(cls.__mro__) |
| 374 | mro = list(cls.__mro__) |
| 375 | for needle in haystack: |
| 376 | if (needle in bases or not hasattr(needle, '__mro__') |
| 377 | or not issubclass(cls, needle)): |
| 378 | continue # either present in the __mro__ already or unrelated |
| 379 | for index, base in enumerate(mro): |
| 380 | if not issubclass(base, needle): |
| 381 | break |
| 382 | if base in bases and not issubclass(needle, base): |
| 383 | # Conflict resolution: put classes present in __mro__ and their |
| 384 | # subclasses first. See test_mro_conflicts() in test_functools.py |
| 385 | # for examples. |
| 386 | index += 1 |
| 387 | mro.insert(index, needle) |
| 388 | return mro |
| 389 | |
| 390 | def _find_impl(cls, registry): |
| 391 | """Returns the best matching implementation for the given class `cls` in |
| 392 | `registry`. Where there is no registered implementation for a specific |
| 393 | type, its method resolution order is used to find a more generic |
| 394 | implementation. |
| 395 | |
| 396 | Note: if `registry` does not contain an implementation for the base |
| 397 | `object` type, this function may return None. |
| 398 | |
| 399 | """ |
| 400 | mro = _compose_mro(cls, registry.keys()) |
| 401 | match = None |
| 402 | for t in mro: |
| 403 | if match is not None: |
| 404 | # If `match` is an ABC but there is another unrelated, equally |
| 405 | # matching ABC. Refuse the temptation to guess. |
| 406 | if (t in registry and not issubclass(match, t) |
| 407 | and match not in cls.__mro__): |
| 408 | raise RuntimeError("Ambiguous dispatch: {} or {}".format( |
| 409 | match, t)) |
| 410 | break |
| 411 | if t in registry: |
| 412 | match = t |
| 413 | return registry.get(match) |
| 414 | |
| 415 | def singledispatch(func): |
| 416 | """Single-dispatch generic function decorator. |
| 417 | |
| 418 | Transforms a function into a generic function, which can have different |
| 419 | behaviours depending upon the type of its first argument. The decorated |
| 420 | function acts as the default implementation, and additional |
| 421 | implementations can be registered using the 'register()' attribute of |
| 422 | the generic function. |
| 423 | |
| 424 | """ |
| 425 | registry = {} |
| 426 | dispatch_cache = WeakKeyDictionary() |
| 427 | cache_token = None |
| 428 | |
| 429 | def dispatch(typ): |
| 430 | """generic_func.dispatch(type) -> <function implementation> |
| 431 | |
| 432 | Runs the dispatch algorithm to return the best available implementation |
| 433 | for the given `type` registered on `generic_func`. |
| 434 | |
| 435 | """ |
| 436 | nonlocal cache_token |
| 437 | if cache_token is not None: |
| 438 | current_token = get_cache_token() |
| 439 | if cache_token != current_token: |
| 440 | dispatch_cache.clear() |
| 441 | cache_token = current_token |
| 442 | try: |
| 443 | impl = dispatch_cache[typ] |
| 444 | except KeyError: |
| 445 | try: |
| 446 | impl = registry[typ] |
| 447 | except KeyError: |
| 448 | impl = _find_impl(typ, registry) |
| 449 | dispatch_cache[typ] = impl |
| 450 | return impl |
| 451 | |
| 452 | def register(typ, func=None): |
| 453 | """generic_func.register(type, func) -> func |
| 454 | |
| 455 | Registers a new implementation for the given `type` on a `generic_func`. |
| 456 | |
| 457 | """ |
| 458 | nonlocal cache_token |
| 459 | if func is None: |
| 460 | return lambda f: register(typ, f) |
| 461 | registry[typ] = func |
| 462 | if cache_token is None and hasattr(typ, '__abstractmethods__'): |
| 463 | cache_token = get_cache_token() |
| 464 | dispatch_cache.clear() |
| 465 | return func |
| 466 | |
| 467 | def wrapper(*args, **kw): |
| 468 | return dispatch(args[0].__class__)(*args, **kw) |
| 469 | |
| 470 | registry[object] = func |
| 471 | wrapper.register = register |
| 472 | wrapper.dispatch = dispatch |
| 473 | wrapper.registry = MappingProxyType(registry) |
| 474 | wrapper._clear_cache = dispatch_cache.clear |
| 475 | update_wrapper(wrapper, func) |
| 476 | return wrapper |