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