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', |
Nick Coghlan | 3daaf5f | 2013-11-04 23:32:16 +1000 | [diff] [blame] | 14 | 'partialmethod', '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 |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 18 | except ImportError: |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 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 |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 22 | from types import MappingProxyType, MethodType |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 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 | """ |
| 58 | for attr in assigned: |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 59 | try: |
| 60 | value = getattr(wrapped, attr) |
| 61 | except AttributeError: |
| 62 | pass |
| 63 | else: |
| 64 | setattr(wrapper, attr, value) |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 65 | for attr in updated: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 66 | getattr(wrapper, attr).update(getattr(wrapped, attr, {})) |
Nick Coghlan | 24c05bc | 2013-07-15 21:13:08 +1000 | [diff] [blame] | 67 | # Issue #17482: set __wrapped__ last so we don't inadvertently copy it |
| 68 | # from the wrapped function when updating __dict__ |
| 69 | wrapper.__wrapped__ = wrapped |
Thomas Wouters | 73e5a5b | 2006-06-08 15:35:45 +0000 | [diff] [blame] | 70 | # Return the wrapper so this can be used as a decorator via partial() |
| 71 | return wrapper |
| 72 | |
| 73 | def wraps(wrapped, |
| 74 | assigned = WRAPPER_ASSIGNMENTS, |
| 75 | updated = WRAPPER_UPDATES): |
| 76 | """Decorator factory to apply update_wrapper() to a wrapper function |
| 77 | |
| 78 | Returns a decorator that invokes update_wrapper() with the decorated |
| 79 | function as the wrapper argument and the arguments to wraps() as the |
| 80 | remaining arguments. Default arguments are as for update_wrapper(). |
| 81 | This is a convenience function to simplify applying partial() to |
| 82 | update_wrapper(). |
| 83 | """ |
| 84 | return partial(update_wrapper, wrapped=wrapped, |
| 85 | assigned=assigned, updated=updated) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 86 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 87 | |
| 88 | ################################################################################ |
| 89 | ### total_ordering class decorator |
| 90 | ################################################################################ |
| 91 | |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 92 | # The correct way to indicate that a comparison operation doesn't |
| 93 | # recognise the other type is to return NotImplemented and let the |
| 94 | # interpreter handle raising TypeError if both operands return |
| 95 | # NotImplemented from their respective comparison methods |
| 96 | # |
| 97 | # This makes the implementation of total_ordering more complicated, since |
| 98 | # we need to be careful not to trigger infinite recursion when two |
| 99 | # different types that both use this decorator encounter each other. |
| 100 | # |
| 101 | # For example, if a type implements __lt__, it's natural to define |
| 102 | # __gt__ as something like: |
| 103 | # |
| 104 | # lambda self, other: not self < other and not self == other |
| 105 | # |
| 106 | # However, using the operator syntax like that ends up invoking the full |
| 107 | # type checking machinery again and means we can end up bouncing back and |
| 108 | # forth between the two operands until we run out of stack space. |
| 109 | # |
| 110 | # The solution is to define helper functions that invoke the appropriate |
| 111 | # magic methods directly, ensuring we only try each operand once, and |
| 112 | # return NotImplemented immediately if it is returned from the |
| 113 | # underlying user provided method. Using this scheme, the __gt__ derived |
| 114 | # from a user provided __lt__ becomes: |
| 115 | # |
| 116 | # lambda self, other: _not_op_and_not_eq(self.__lt__, self, other)) |
| 117 | |
| 118 | def _not_op(op, other): |
| 119 | # "not a < b" handles "a >= b" |
| 120 | # "not a <= b" handles "a > b" |
| 121 | # "not a >= b" handles "a < b" |
| 122 | # "not a > b" handles "a <= b" |
| 123 | op_result = op(other) |
| 124 | if op_result is NotImplemented: |
| 125 | return NotImplemented |
| 126 | return not op_result |
| 127 | |
| 128 | def _op_or_eq(op, self, other): |
| 129 | # "a < b or a == b" handles "a <= b" |
| 130 | # "a > b or a == b" handles "a >= b" |
| 131 | op_result = op(other) |
| 132 | if op_result is NotImplemented: |
| 133 | return NotImplemented |
| 134 | return op_result or self == other |
| 135 | |
| 136 | def _not_op_and_not_eq(op, self, other): |
| 137 | # "not (a < b or a == b)" handles "a > b" |
| 138 | # "not a < b and a != b" is equivalent |
| 139 | # "not (a > b or a == b)" handles "a < b" |
| 140 | # "not a > b and a != b" is equivalent |
| 141 | op_result = op(other) |
| 142 | if op_result is NotImplemented: |
| 143 | return NotImplemented |
| 144 | return not op_result and self != other |
| 145 | |
| 146 | def _not_op_or_eq(op, self, other): |
| 147 | # "not a <= b or a == b" handles "a >= b" |
| 148 | # "not a >= b or a == b" handles "a <= b" |
| 149 | op_result = op(other) |
| 150 | if op_result is NotImplemented: |
| 151 | return NotImplemented |
| 152 | return not op_result or self == other |
| 153 | |
| 154 | def _op_and_not_eq(op, self, other): |
| 155 | # "a <= b and not a == b" handles "a < b" |
| 156 | # "a >= b and not a == b" handles "a > b" |
| 157 | op_result = op(other) |
| 158 | if op_result is NotImplemented: |
| 159 | return NotImplemented |
| 160 | return op_result and self != other |
| 161 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 162 | def total_ordering(cls): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 163 | """Class decorator that fills in missing ordering methods""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 164 | convert = { |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 165 | '__lt__': [('__gt__', lambda self, other: _not_op_and_not_eq(self.__lt__, self, other)), |
| 166 | ('__le__', lambda self, other: _op_or_eq(self.__lt__, self, other)), |
| 167 | ('__ge__', lambda self, other: _not_op(self.__lt__, other))], |
| 168 | '__le__': [('__ge__', lambda self, other: _not_op_or_eq(self.__le__, self, other)), |
| 169 | ('__lt__', lambda self, other: _op_and_not_eq(self.__le__, self, other)), |
| 170 | ('__gt__', lambda self, other: _not_op(self.__le__, other))], |
| 171 | '__gt__': [('__lt__', lambda self, other: _not_op_and_not_eq(self.__gt__, self, other)), |
| 172 | ('__ge__', lambda self, other: _op_or_eq(self.__gt__, self, other)), |
| 173 | ('__le__', lambda self, other: _not_op(self.__gt__, other))], |
| 174 | '__ge__': [('__le__', lambda self, other: _not_op_or_eq(self.__ge__, self, other)), |
| 175 | ('__gt__', lambda self, other: _op_and_not_eq(self.__ge__, self, other)), |
| 176 | ('__lt__', lambda self, other: _not_op(self.__ge__, other))] |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 177 | } |
Raymond Hettinger | 3255c63 | 2010-09-16 00:31:21 +0000 | [diff] [blame] | 178 | # Find user-defined comparisons (not those inherited from object). |
Raymond Hettinger | 1006bd4 | 2010-09-14 22:55:13 +0000 | [diff] [blame] | 179 | 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] | 180 | if not roots: |
| 181 | raise ValueError('must define at least one ordering operation: < > <= >=') |
| 182 | root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__ |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 183 | for opname, opfunc in convert[root]: |
| 184 | if opname not in roots: |
| 185 | opfunc.__name__ = opname |
| 186 | opfunc.__doc__ = getattr(int, opname).__doc__ |
| 187 | setattr(cls, opname, opfunc) |
| 188 | return cls |
| 189 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 190 | |
| 191 | ################################################################################ |
| 192 | ### cmp_to_key() function converter |
| 193 | ################################################################################ |
| 194 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 195 | def cmp_to_key(mycmp): |
Georg Brandl | e5a2673 | 2010-05-19 21:06:36 +0000 | [diff] [blame] | 196 | """Convert a cmp= function into a key= function""" |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 197 | class K(object): |
Raymond Hettinger | a0d1d96 | 2011-03-21 17:50:28 -0700 | [diff] [blame] | 198 | __slots__ = ['obj'] |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 199 | def __init__(self, obj): |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 200 | self.obj = obj |
| 201 | def __lt__(self, other): |
| 202 | return mycmp(self.obj, other.obj) < 0 |
| 203 | def __gt__(self, other): |
| 204 | return mycmp(self.obj, other.obj) > 0 |
| 205 | def __eq__(self, other): |
| 206 | return mycmp(self.obj, other.obj) == 0 |
| 207 | def __le__(self, other): |
| 208 | return mycmp(self.obj, other.obj) <= 0 |
| 209 | def __ge__(self, other): |
| 210 | return mycmp(self.obj, other.obj) >= 0 |
| 211 | def __ne__(self, other): |
| 212 | return mycmp(self.obj, other.obj) != 0 |
Raymond Hettinger | 003be52 | 2011-05-03 11:01:32 -0700 | [diff] [blame] | 213 | __hash__ = None |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 214 | return K |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 215 | |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 216 | try: |
| 217 | from _functools import cmp_to_key |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 218 | except ImportError: |
Raymond Hettinger | 7ab9e22 | 2011-04-05 02:33:54 -0700 | [diff] [blame] | 219 | pass |
| 220 | |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 221 | |
| 222 | ################################################################################ |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 223 | ### partial() argument application |
| 224 | ################################################################################ |
| 225 | |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 226 | # Purely functional, no descriptor behaviour |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 227 | def partial(func, *args, **keywords): |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 228 | """New function with partial application of the given arguments |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 229 | and keywords. |
| 230 | """ |
| 231 | def newfunc(*fargs, **fkeywords): |
| 232 | newkeywords = keywords.copy() |
| 233 | newkeywords.update(fkeywords) |
| 234 | return func(*(args + fargs), **newkeywords) |
| 235 | newfunc.func = func |
| 236 | newfunc.args = args |
| 237 | newfunc.keywords = keywords |
| 238 | return newfunc |
| 239 | |
| 240 | try: |
| 241 | from _functools import partial |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 242 | except ImportError: |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 243 | pass |
| 244 | |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 245 | # Descriptor version |
| 246 | class partialmethod(object): |
| 247 | """Method descriptor with partial application of the given arguments |
| 248 | and keywords. |
| 249 | |
| 250 | Supports wrapping existing descriptors and handles non-descriptor |
| 251 | callables as instance methods. |
| 252 | """ |
| 253 | |
| 254 | def __init__(self, func, *args, **keywords): |
| 255 | if not callable(func) and not hasattr(func, "__get__"): |
| 256 | raise TypeError("{!r} is not callable or a descriptor" |
| 257 | .format(func)) |
| 258 | |
| 259 | # func could be a descriptor like classmethod which isn't callable, |
| 260 | # so we can't inherit from partial (it verifies func is callable) |
| 261 | if isinstance(func, partialmethod): |
| 262 | # flattening is mandatory in order to place cls/self before all |
| 263 | # other arguments |
| 264 | # it's also more efficient since only one function will be called |
| 265 | self.func = func.func |
| 266 | self.args = func.args + args |
| 267 | self.keywords = func.keywords.copy() |
| 268 | self.keywords.update(keywords) |
| 269 | else: |
| 270 | self.func = func |
| 271 | self.args = args |
| 272 | self.keywords = keywords |
| 273 | |
| 274 | def __repr__(self): |
| 275 | args = ", ".join(map(repr, self.args)) |
| 276 | keywords = ", ".join("{}={!r}".format(k, v) |
| 277 | for k, v in self.keywords.items()) |
| 278 | format_string = "{module}.{cls}({func}, {args}, {keywords})" |
| 279 | return format_string.format(module=self.__class__.__module__, |
| 280 | cls=self.__class__.__name__, |
| 281 | func=self.func, |
| 282 | args=args, |
| 283 | keywords=keywords) |
| 284 | |
| 285 | def _make_unbound_method(self): |
| 286 | def _method(*args, **keywords): |
| 287 | call_keywords = self.keywords.copy() |
| 288 | call_keywords.update(keywords) |
| 289 | cls_or_self, *rest = args |
| 290 | call_args = (cls_or_self,) + self.args + tuple(rest) |
| 291 | return self.func(*call_args, **call_keywords) |
| 292 | _method.__isabstractmethod__ = self.__isabstractmethod__ |
Yury Selivanov | da5fe4f | 2014-01-27 17:28:37 -0500 | [diff] [blame] | 293 | _method._partialmethod = self |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 294 | return _method |
| 295 | |
| 296 | def __get__(self, obj, cls): |
| 297 | get = getattr(self.func, "__get__", None) |
| 298 | result = None |
| 299 | if get is not None: |
| 300 | new_func = get(obj, cls) |
| 301 | if new_func is not self.func: |
| 302 | # Assume __get__ returning something new indicates the |
| 303 | # creation of an appropriate callable |
| 304 | result = partial(new_func, *self.args, **self.keywords) |
| 305 | try: |
| 306 | result.__self__ = new_func.__self__ |
| 307 | except AttributeError: |
| 308 | pass |
| 309 | if result is None: |
| 310 | # If the underlying descriptor didn't do anything, treat this |
| 311 | # like an instance method |
| 312 | result = self._make_unbound_method().__get__(obj, cls) |
| 313 | return result |
| 314 | |
| 315 | @property |
| 316 | def __isabstractmethod__(self): |
| 317 | return getattr(self.func, "__isabstractmethod__", False) |
| 318 | |
Antoine Pitrou | b5b3714 | 2012-11-13 21:35:40 +0100 | [diff] [blame] | 319 | |
| 320 | ################################################################################ |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 321 | ### LRU Cache function decorator |
| 322 | ################################################################################ |
| 323 | |
Raymond Hettinger | dce583e | 2012-03-16 22:12:20 -0700 | [diff] [blame] | 324 | _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 325 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 326 | class _HashedSeq(list): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 327 | """ This class guarantees that hash() will be called no more than once |
| 328 | per element. This is important because the lru_cache() will hash |
| 329 | the key multiple times on a cache miss. |
| 330 | |
| 331 | """ |
| 332 | |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 333 | __slots__ = 'hashvalue' |
| 334 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 335 | def __init__(self, tup, hash=hash): |
| 336 | self[:] = tup |
| 337 | self.hashvalue = hash(tup) |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 338 | |
| 339 | def __hash__(self): |
| 340 | return self.hashvalue |
| 341 | |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 342 | def _make_key(args, kwds, typed, |
| 343 | kwd_mark = (object(),), |
| 344 | fasttypes = {int, str, frozenset, type(None)}, |
| 345 | sorted=sorted, tuple=tuple, type=type, len=len): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 346 | """Make a cache key from optionally typed positional and keyword arguments |
| 347 | |
| 348 | The key is constructed in a way that is flat as possible rather than |
| 349 | as a nested structure that would take more memory. |
| 350 | |
| 351 | If there is only a single argument and its data type is known to cache |
| 352 | its hash value, then that argument is returned without a wrapper. This |
| 353 | saves space and improves lookup speed. |
| 354 | |
| 355 | """ |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 356 | key = args |
| 357 | if kwds: |
| 358 | sorted_items = sorted(kwds.items()) |
| 359 | key += kwd_mark |
| 360 | for item in sorted_items: |
| 361 | key += item |
| 362 | if typed: |
| 363 | key += tuple(type(v) for v in args) |
| 364 | if kwds: |
| 365 | key += tuple(type(v) for k, v in sorted_items) |
| 366 | elif len(key) == 1 and type(key[0]) in fasttypes: |
| 367 | return key[0] |
| 368 | return _HashedSeq(key) |
| 369 | |
Raymond Hettinger | 010ce32 | 2012-05-19 21:20:48 -0700 | [diff] [blame] | 370 | def lru_cache(maxsize=128, typed=False): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 371 | """Least-recently-used cache decorator. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 372 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 373 | If *maxsize* is set to None, the LRU features are disabled and the cache |
| 374 | can grow without bound. |
| 375 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 376 | If *typed* is True, arguments of different types will be cached separately. |
| 377 | For example, f(3.0) and f(3) will be treated as distinct calls with |
| 378 | distinct results. |
| 379 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 380 | Arguments to the cached function must be hashable. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 381 | |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 382 | View the cache statistics named tuple (hits, misses, maxsize, currsize) |
| 383 | 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] | 384 | Access the underlying function with f.__wrapped__. |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 385 | |
| 386 | See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 387 | |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 388 | """ |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 389 | |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 390 | # Users should only access the lru_cache through its public API: |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 391 | # cache_info, cache_clear, and f.__wrapped__ |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 392 | # The internals of the lru_cache are encapsulated for thread safety and |
| 393 | # to allow the implementation to change (including a possible C version). |
| 394 | |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 395 | # Constants shared by all lru cache instances: |
Raymond Hettinger | b6b98c0 | 2012-04-29 18:09:02 -0700 | [diff] [blame] | 396 | sentinel = object() # unique object used to signal cache misses |
Raymond Hettinger | 0c9050c | 2012-06-04 00:21:14 -0700 | [diff] [blame] | 397 | make_key = _make_key # build a key from the function arguments |
Raymond Hettinger | 9f0ab9f | 2012-04-29 14:55:27 -0700 | [diff] [blame] | 398 | PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields |
| 399 | |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 400 | def decorating_function(user_function): |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 401 | cache = {} |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 402 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 403 | full = False |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 404 | 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] | 405 | lock = RLock() # because linkedlist updates aren't threadsafe |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 406 | root = [] # root of the circular doubly linked list |
| 407 | root[:] = [root, root, None, None] # initialize by pointing to self |
Raymond Hettinger | 6e8c817 | 2012-03-16 16:53:05 -0700 | [diff] [blame] | 408 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 409 | if maxsize == 0: |
| 410 | |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 411 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 412 | # No caching -- just a statistics update after a successful call |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 413 | nonlocal misses |
Raymond Hettinger | 7dabfed | 2012-03-17 15:11:09 -0700 | [diff] [blame] | 414 | result = user_function(*args, **kwds) |
Raymond Hettinger | 7e0c581 | 2012-03-17 15:10:24 -0700 | [diff] [blame] | 415 | misses += 1 |
| 416 | return result |
| 417 | |
| 418 | elif maxsize is None: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 419 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 420 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 421 | # Simple caching without ordering or size limit |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 422 | nonlocal hits, misses |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 423 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 7f7a5a7 | 2012-03-30 21:50:40 -0700 | [diff] [blame] | 424 | result = cache_get(key, sentinel) |
| 425 | if result is not sentinel: |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 426 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 427 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 428 | result = user_function(*args, **kwds) |
| 429 | cache[key] = result |
| 430 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 431 | return result |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 432 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 433 | else: |
Raymond Hettinger | bc8e81d | 2012-03-17 00:24:09 -0700 | [diff] [blame] | 434 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 435 | def wrapper(*args, **kwds): |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 436 | # Size limited caching that tracks accesses by recency |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 437 | nonlocal root, hits, misses, full |
Raymond Hettinger | 9acbb60 | 2012-04-30 22:32:16 -0700 | [diff] [blame] | 438 | key = make_key(args, kwds, typed) |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 439 | with lock: |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 440 | link = cache_get(key) |
| 441 | if link is not None: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 442 | # Move the link to the front of the circular queue |
| 443 | link_prev, link_next, _key, result = link |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 444 | link_prev[NEXT] = link_next |
| 445 | link_next[PREV] = link_prev |
| 446 | last = root[PREV] |
| 447 | last[NEXT] = root[PREV] = link |
| 448 | link[PREV] = last |
| 449 | link[NEXT] = root |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 450 | hits += 1 |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 451 | return result |
Raymond Hettinger | 4b779b3 | 2011-10-15 23:50:42 -0700 | [diff] [blame] | 452 | result = user_function(*args, **kwds) |
| 453 | with lock: |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 454 | if key in cache: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 455 | # Getting here means that this same key was added to the |
| 456 | # cache while the lock was released. Since the link |
Raymond Hettinger | 34d94a2 | 2012-04-30 14:14:28 -0700 | [diff] [blame] | 457 | # update is already done, we need only return the |
| 458 | # computed result and update the count of misses. |
| 459 | pass |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 460 | elif full: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 461 | # Use the old root to store the new key and result. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 462 | oldroot = root |
| 463 | oldroot[KEY] = key |
| 464 | oldroot[RESULT] = result |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 465 | # Empty the oldest link and make it the new root. |
| 466 | # Keep a reference to the old key and old result to |
| 467 | # prevent their ref counts from going to zero during the |
| 468 | # update. That will prevent potentially arbitrary object |
| 469 | # clean-up code (i.e. __del__) from running while we're |
| 470 | # still adjusting the links. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 471 | root = oldroot[NEXT] |
| 472 | oldkey = root[KEY] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 473 | oldresult = root[RESULT] |
Raymond Hettinger | c689785 | 2012-03-31 02:19:06 -0700 | [diff] [blame] | 474 | root[KEY] = root[RESULT] = None |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 475 | # Now update the cache dictionary. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 476 | del cache[oldkey] |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 477 | # Save the potentially reentrant cache[key] assignment |
| 478 | # for last, after the root and links have been put in |
| 479 | # a consistent state. |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 480 | cache[key] = oldroot |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 481 | else: |
Raymond Hettinger | f96b2b0 | 2013-03-08 21:11:55 -0700 | [diff] [blame] | 482 | # Put result in a new link at the front of the queue. |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 483 | last = root[PREV] |
| 484 | link = [last, root, key, result] |
Raymond Hettinger | f2c17a9 | 2013-03-04 03:34:09 -0500 | [diff] [blame] | 485 | last[NEXT] = root[PREV] = cache[key] = link |
Raymond Hettinger | bb5f480 | 2013-03-04 04:20:46 -0500 | [diff] [blame] | 486 | full = (len(cache) >= maxsize) |
Raymond Hettinger | ec0e910 | 2012-03-16 01:16:31 -0700 | [diff] [blame] | 487 | misses += 1 |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 488 | return result |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 489 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 490 | def cache_info(): |
Raymond Hettinger | 5e20bab | 2010-11-30 07:13:04 +0000 | [diff] [blame] | 491 | """Report cache statistics""" |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 492 | with lock: |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 493 | return _CacheInfo(hits, misses, maxsize, len(cache)) |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 494 | |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 495 | def cache_clear(): |
Benjamin Peterson | 1f594ad | 2010-08-08 13:17:07 +0000 | [diff] [blame] | 496 | """Clear the cache and cache statistics""" |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 497 | nonlocal hits, misses, full |
Raymond Hettinger | cbe8813 | 2010-08-14 22:22:10 +0000 | [diff] [blame] | 498 | with lock: |
| 499 | cache.clear() |
Benjamin Peterson | 954cf57 | 2012-03-16 18:22:26 -0500 | [diff] [blame] | 500 | root[:] = [root, root, None, None] |
Raymond Hettinger | 832edde | 2013-02-17 00:08:45 -0800 | [diff] [blame] | 501 | hits = misses = 0 |
Raymond Hettinger | 018b4fb | 2012-04-30 20:48:55 -0700 | [diff] [blame] | 502 | full = False |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 503 | |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 504 | wrapper.cache_info = cache_info |
Raymond Hettinger | 02566ec | 2010-09-04 22:46:06 +0000 | [diff] [blame] | 505 | wrapper.cache_clear = cache_clear |
Raymond Hettinger | 1ff50df | 2012-03-30 13:15:48 -0700 | [diff] [blame] | 506 | return update_wrapper(wrapper, user_function) |
Raymond Hettinger | 5fa40c0 | 2010-11-25 08:11:57 +0000 | [diff] [blame] | 507 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 508 | return decorating_function |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 509 | |
| 510 | |
| 511 | ################################################################################ |
| 512 | ### singledispatch() - single-dispatch generic function decorator |
| 513 | ################################################################################ |
| 514 | |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 515 | def _c3_merge(sequences): |
| 516 | """Merges MROs in *sequences* to a single MRO using the C3 algorithm. |
| 517 | |
| 518 | Adapted from http://www.python.org/download/releases/2.3/mro/. |
| 519 | |
| 520 | """ |
| 521 | result = [] |
| 522 | while True: |
| 523 | sequences = [s for s in sequences if s] # purge empty sequences |
| 524 | if not sequences: |
| 525 | return result |
| 526 | for s1 in sequences: # find merge candidates among seq heads |
| 527 | candidate = s1[0] |
| 528 | for s2 in sequences: |
| 529 | if candidate in s2[1:]: |
| 530 | candidate = None |
| 531 | break # reject the current head, it appears later |
| 532 | else: |
| 533 | break |
| 534 | if not candidate: |
| 535 | raise RuntimeError("Inconsistent hierarchy") |
| 536 | result.append(candidate) |
| 537 | # remove the chosen candidate |
| 538 | for seq in sequences: |
| 539 | if seq[0] == candidate: |
| 540 | del seq[0] |
| 541 | |
| 542 | def _c3_mro(cls, abcs=None): |
| 543 | """Computes the method resolution order using extended C3 linearization. |
| 544 | |
| 545 | If no *abcs* are given, the algorithm works exactly like the built-in C3 |
| 546 | linearization used for method resolution. |
| 547 | |
| 548 | If given, *abcs* is a list of abstract base classes that should be inserted |
| 549 | into the resulting MRO. Unrelated ABCs are ignored and don't end up in the |
| 550 | result. The algorithm inserts ABCs where their functionality is introduced, |
| 551 | i.e. issubclass(cls, abc) returns True for the class itself but returns |
| 552 | False for all its direct base classes. Implicit ABCs for a given class |
| 553 | (either registered or inferred from the presence of a special method like |
| 554 | __len__) are inserted directly after the last ABC explicitly listed in the |
| 555 | MRO of said class. If two implicit ABCs end up next to each other in the |
| 556 | resulting MRO, their ordering depends on the order of types in *abcs*. |
| 557 | |
| 558 | """ |
| 559 | for i, base in enumerate(reversed(cls.__bases__)): |
| 560 | if hasattr(base, '__abstractmethods__'): |
| 561 | boundary = len(cls.__bases__) - i |
| 562 | break # Bases up to the last explicit ABC are considered first. |
| 563 | else: |
| 564 | boundary = 0 |
| 565 | abcs = list(abcs) if abcs else [] |
| 566 | explicit_bases = list(cls.__bases__[:boundary]) |
| 567 | abstract_bases = [] |
| 568 | other_bases = list(cls.__bases__[boundary:]) |
| 569 | for base in abcs: |
| 570 | if issubclass(cls, base) and not any( |
| 571 | issubclass(b, base) for b in cls.__bases__ |
| 572 | ): |
| 573 | # If *cls* is the class that introduces behaviour described by |
| 574 | # an ABC *base*, insert said ABC to its MRO. |
| 575 | abstract_bases.append(base) |
| 576 | for base in abstract_bases: |
| 577 | abcs.remove(base) |
| 578 | explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases] |
| 579 | abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases] |
| 580 | other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases] |
| 581 | return _c3_merge( |
| 582 | [[cls]] + |
| 583 | explicit_c3_mros + abstract_c3_mros + other_c3_mros + |
| 584 | [explicit_bases] + [abstract_bases] + [other_bases] |
| 585 | ) |
| 586 | |
| 587 | def _compose_mro(cls, types): |
| 588 | """Calculates the method resolution order for a given class *cls*. |
| 589 | |
| 590 | Includes relevant abstract base classes (with their respective bases) from |
| 591 | the *types* iterable. Uses a modified C3 linearization algorithm. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 592 | |
| 593 | """ |
| 594 | bases = set(cls.__mro__) |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 595 | # Remove entries which are already present in the __mro__ or unrelated. |
| 596 | def is_related(typ): |
| 597 | return (typ not in bases and hasattr(typ, '__mro__') |
| 598 | and issubclass(cls, typ)) |
| 599 | types = [n for n in types if is_related(n)] |
| 600 | # Remove entries which are strict bases of other entries (they will end up |
| 601 | # in the MRO anyway. |
| 602 | def is_strict_base(typ): |
| 603 | for other in types: |
| 604 | if typ != other and typ in other.__mro__: |
| 605 | return True |
| 606 | return False |
| 607 | types = [n for n in types if not is_strict_base(n)] |
| 608 | # Subclasses of the ABCs in *types* which are also implemented by |
| 609 | # *cls* can be used to stabilize ABC ordering. |
| 610 | type_set = set(types) |
| 611 | mro = [] |
| 612 | for typ in types: |
| 613 | found = [] |
| 614 | for sub in typ.__subclasses__(): |
| 615 | if sub not in bases and issubclass(cls, sub): |
| 616 | found.append([s for s in sub.__mro__ if s in type_set]) |
| 617 | if not found: |
| 618 | mro.append(typ) |
| 619 | continue |
| 620 | # Favor subclasses with the biggest number of useful bases |
| 621 | found.sort(key=len, reverse=True) |
| 622 | for sub in found: |
| 623 | for subcls in sub: |
| 624 | if subcls not in mro: |
| 625 | mro.append(subcls) |
| 626 | return _c3_mro(cls, abcs=mro) |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 627 | |
| 628 | def _find_impl(cls, registry): |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 629 | """Returns the best matching implementation from *registry* for type *cls*. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 630 | |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 631 | Where there is no registered implementation for a specific type, its method |
| 632 | resolution order is used to find a more generic implementation. |
| 633 | |
| 634 | Note: if *registry* does not contain an implementation for the base |
| 635 | *object* type, this function may return None. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 636 | |
| 637 | """ |
| 638 | mro = _compose_mro(cls, registry.keys()) |
| 639 | match = None |
| 640 | for t in mro: |
| 641 | if match is not None: |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 642 | # If *match* is an implicit ABC but there is another unrelated, |
| 643 | # equally matching implicit ABC, refuse the temptation to guess. |
| 644 | if (t in registry and t not in cls.__mro__ |
| 645 | and match not in cls.__mro__ |
| 646 | and not issubclass(match, t)): |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 647 | raise RuntimeError("Ambiguous dispatch: {} or {}".format( |
| 648 | match, t)) |
| 649 | break |
| 650 | if t in registry: |
| 651 | match = t |
| 652 | return registry.get(match) |
| 653 | |
| 654 | def singledispatch(func): |
| 655 | """Single-dispatch generic function decorator. |
| 656 | |
| 657 | Transforms a function into a generic function, which can have different |
| 658 | behaviours depending upon the type of its first argument. The decorated |
| 659 | function acts as the default implementation, and additional |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 660 | implementations can be registered using the register() attribute of the |
| 661 | generic function. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 662 | |
| 663 | """ |
| 664 | registry = {} |
| 665 | dispatch_cache = WeakKeyDictionary() |
| 666 | cache_token = None |
| 667 | |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 668 | def dispatch(cls): |
| 669 | """generic_func.dispatch(cls) -> <function implementation> |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 670 | |
| 671 | Runs the dispatch algorithm to return the best available implementation |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 672 | for the given *cls* registered on *generic_func*. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 673 | |
| 674 | """ |
| 675 | nonlocal cache_token |
| 676 | if cache_token is not None: |
| 677 | current_token = get_cache_token() |
| 678 | if cache_token != current_token: |
| 679 | dispatch_cache.clear() |
| 680 | cache_token = current_token |
| 681 | try: |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 682 | impl = dispatch_cache[cls] |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 683 | except KeyError: |
| 684 | try: |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 685 | impl = registry[cls] |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 686 | except KeyError: |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 687 | impl = _find_impl(cls, registry) |
| 688 | dispatch_cache[cls] = impl |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 689 | return impl |
| 690 | |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 691 | def register(cls, func=None): |
| 692 | """generic_func.register(cls, func) -> func |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 693 | |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 694 | Registers a new implementation for the given *cls* on a *generic_func*. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 695 | |
| 696 | """ |
| 697 | nonlocal cache_token |
| 698 | if func is None: |
Łukasz Langa | 3720c77 | 2013-07-01 16:00:38 +0200 | [diff] [blame] | 699 | return lambda f: register(cls, f) |
| 700 | registry[cls] = func |
| 701 | if cache_token is None and hasattr(cls, '__abstractmethods__'): |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 702 | cache_token = get_cache_token() |
| 703 | dispatch_cache.clear() |
| 704 | return func |
| 705 | |
| 706 | def wrapper(*args, **kw): |
| 707 | return dispatch(args[0].__class__)(*args, **kw) |
| 708 | |
| 709 | registry[object] = func |
| 710 | wrapper.register = register |
| 711 | wrapper.dispatch = dispatch |
| 712 | wrapper.registry = MappingProxyType(registry) |
| 713 | wrapper._clear_cache = dispatch_cache.clear |
| 714 | update_wrapper(wrapper, func) |
| 715 | return wrapper |