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