blob: fa5bfdef091a6b9991d28f4cd086162ebde22b0c [file] [log] [blame]
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001"""functools.py - Tools for working with functions and callable objects
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002"""
3# Python module wrapper for _functools C module
4# to allow utilities written in Python to be added
5# to the functools module.
Łukasz Langa6f692512013-06-05 12:20:24 +02006# 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 Wouters73e5a5b2006-06-08 15:35:45 +000010# See C source code for _functools credits/copyright
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000011
Georg Brandl2e7346a2010-07-31 18:09:23 +000012__all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
Łukasz Langa6f692512013-06-05 12:20:24 +020013 'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial',
Nick Coghlan3daaf5f2013-11-04 23:32:16 +100014 'partialmethod', 'singledispatch']
Georg Brandl2e7346a2010-07-31 18:09:23 +000015
Antoine Pitroub5b37142012-11-13 21:35:40 +010016try:
17 from _functools import reduce
Brett Cannoncd171c82013-07-04 17:43:24 -040018except ImportError:
Antoine Pitroub5b37142012-11-13 21:35:40 +010019 pass
Łukasz Langa6f692512013-06-05 12:20:24 +020020from abc import get_cache_token
Raymond Hettingerec0e9102012-03-16 01:16:31 -070021from collections import namedtuple
Victor Stinner7fa767e2014-03-20 09:16:38 +010022from types import MappingProxyType
Łukasz Langa6f692512013-06-05 12:20:24 +020023from weakref import WeakKeyDictionary
Raymond Hettingercbe88132010-08-14 22:22:10 +000024try:
Raymond Hettingerfd541172013-03-01 03:47:57 -080025 from _thread import RLock
Raymond Hettingercbe88132010-08-14 22:22:10 +000026except:
Raymond Hettinger409f6632013-03-01 23:20:13 -080027 class RLock:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -070028 'Dummy reentrant lock for builds without threads'
Raymond Hettinger409f6632013-03-01 23:20:13 -080029 def __enter__(self): pass
30 def __exit__(self, exctype, excinst, exctb): pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000031
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -070032
33################################################################################
34### update_wrapper() and wraps() decorator
35################################################################################
36
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000037# update_wrapper() and wraps() are tools to help write
38# wrapper functions that can handle naive introspection
39
Meador Ingeff7f64c2011-12-11 22:37:31 -060040WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
41 '__annotations__')
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000042WRAPPER_UPDATES = ('__dict__',)
43def 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 Wouters89f507f2006-12-13 04:49:30 +000054 updated is a tuple naming the attributes of the wrapper that
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000055 are updated with the corresponding attribute from the wrapped
56 function (defaults to functools.WRAPPER_UPDATES)
57 """
58 for attr in assigned:
Nick Coghlan98876832010-08-17 06:17:18 +000059 try:
60 value = getattr(wrapped, attr)
61 except AttributeError:
62 pass
63 else:
64 setattr(wrapper, attr, value)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000065 for attr in updated:
Thomas Wouters89f507f2006-12-13 04:49:30 +000066 getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
Nick Coghlan24c05bc2013-07-15 21:13:08 +100067 # 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 Wouters73e5a5b2006-06-08 15:35:45 +000070 # Return the wrapper so this can be used as a decorator via partial()
71 return wrapper
72
73def 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 Hettingerc50846a2010-04-05 18:56:31 +000086
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -070087
88################################################################################
89### total_ordering class decorator
90################################################################################
91
Raymond Hettinger0603d302015-01-05 21:52:10 -080092# 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 Coghlanf05d9812013-10-02 00:02:03 +100096
Raymond Hettinger0603d302015-01-05 21:52:10 -080097def _gt_from_lt(self, other):
98 'Return a > b. Computed by @total_ordering from (not a < b) and (a != b).'
99 op_result = self.__lt__(other)
Nick Coghlanf05d9812013-10-02 00:02:03 +1000100 if op_result is NotImplemented:
Raymond Hettingere5db8632015-01-06 22:16:10 -0800101 return op_result
Nick Coghlanf05d9812013-10-02 00:02:03 +1000102 return not op_result and self != other
103
Raymond Hettinger0603d302015-01-05 21:52:10 -0800104def _le_from_lt(self, other):
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
109def _ge_from_lt(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800113 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800114 return not op_result
115
116def _ge_from_le(self, other):
117 'Return a >= b. Computed by @total_ordering from (not a <= b) or (a == b).'
118 op_result = self.__le__(other)
Nick Coghlanf05d9812013-10-02 00:02:03 +1000119 if op_result is NotImplemented:
Raymond Hettingere5db8632015-01-06 22:16:10 -0800120 return op_result
Nick Coghlanf05d9812013-10-02 00:02:03 +1000121 return not op_result or self == other
122
Raymond Hettinger0603d302015-01-05 21:52:10 -0800123def _lt_from_le(self, other):
124 'Return a < b. Computed by @total_ordering from (a <= b) and (a != b).'
125 op_result = self.__le__(other)
Nick Coghlanf05d9812013-10-02 00:02:03 +1000126 if op_result is NotImplemented:
Raymond Hettingere5db8632015-01-06 22:16:10 -0800127 return op_result
Nick Coghlanf05d9812013-10-02 00:02:03 +1000128 return op_result and self != other
129
Raymond Hettinger0603d302015-01-05 21:52:10 -0800130def _gt_from_le(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800134 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800135 return not op_result
136
137def _lt_from_gt(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800141 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800142 return not op_result and self != other
143
144def _ge_from_gt(self, other):
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
149def _le_from_gt(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800153 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800154 return not op_result
155
156def _le_from_ge(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800160 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800161 return not op_result or self == other
162
163def _gt_from_ge(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800167 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800168 return op_result and self != other
169
170def _lt_from_ge(self, other):
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 Hettingere5db8632015-01-06 22:16:10 -0800174 return op_result
Raymond Hettinger0603d302015-01-05 21:52:10 -0800175 return not op_result
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000176
Raymond Hettinger1a8ada82015-01-13 22:57:35 -0800177_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 Hettingerc50846a2010-04-05 18:56:31 +0000192def total_ordering(cls):
Georg Brandle5a26732010-05-19 21:06:36 +0000193 """Class decorator that fills in missing ordering methods"""
Raymond Hettinger3255c632010-09-16 00:31:21 +0000194 # Find user-defined comparisons (not those inherited from object).
Raymond Hettinger1a8ada82015-01-13 22:57:35 -0800195 roots = [op for op in _convert if getattr(cls, op, None) is not getattr(object, op, None)]
Raymond Hettinger56de7e22010-04-10 16:59:03 +0000196 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 Hettinger1a8ada82015-01-13 22:57:35 -0800199 for opname, opfunc in _convert[root]:
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000200 if opname not in roots:
201 opfunc.__name__ = opname
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000202 setattr(cls, opname, opfunc)
203 return cls
204
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700205
206################################################################################
207### cmp_to_key() function converter
208################################################################################
209
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000210def cmp_to_key(mycmp):
Georg Brandle5a26732010-05-19 21:06:36 +0000211 """Convert a cmp= function into a key= function"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000212 class K(object):
Raymond Hettingera0d1d962011-03-21 17:50:28 -0700213 __slots__ = ['obj']
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700214 def __init__(self, obj):
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000215 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
226 def __ne__(self, other):
227 return mycmp(self.obj, other.obj) != 0
Raymond Hettinger003be522011-05-03 11:01:32 -0700228 __hash__ = None
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000229 return K
Georg Brandl2e7346a2010-07-31 18:09:23 +0000230
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700231try:
232 from _functools import cmp_to_key
Brett Cannoncd171c82013-07-04 17:43:24 -0400233except ImportError:
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700234 pass
235
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700236
237################################################################################
Antoine Pitroub5b37142012-11-13 21:35:40 +0100238### partial() argument application
239################################################################################
240
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000241# Purely functional, no descriptor behaviour
Antoine Pitroub5b37142012-11-13 21:35:40 +0100242def partial(func, *args, **keywords):
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000243 """New function with partial application of the given arguments
Antoine Pitroub5b37142012-11-13 21:35:40 +0100244 and keywords.
245 """
246 def newfunc(*fargs, **fkeywords):
247 newkeywords = keywords.copy()
248 newkeywords.update(fkeywords)
249 return func(*(args + fargs), **newkeywords)
250 newfunc.func = func
251 newfunc.args = args
252 newfunc.keywords = keywords
253 return newfunc
254
255try:
256 from _functools import partial
Brett Cannoncd171c82013-07-04 17:43:24 -0400257except ImportError:
Antoine Pitroub5b37142012-11-13 21:35:40 +0100258 pass
259
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000260# Descriptor version
261class partialmethod(object):
262 """Method descriptor with partial application of the given arguments
263 and keywords.
264
265 Supports wrapping existing descriptors and handles non-descriptor
266 callables as instance methods.
267 """
268
269 def __init__(self, func, *args, **keywords):
270 if not callable(func) and not hasattr(func, "__get__"):
271 raise TypeError("{!r} is not callable or a descriptor"
272 .format(func))
273
274 # func could be a descriptor like classmethod which isn't callable,
275 # so we can't inherit from partial (it verifies func is callable)
276 if isinstance(func, partialmethod):
277 # flattening is mandatory in order to place cls/self before all
278 # other arguments
279 # it's also more efficient since only one function will be called
280 self.func = func.func
281 self.args = func.args + args
282 self.keywords = func.keywords.copy()
283 self.keywords.update(keywords)
284 else:
285 self.func = func
286 self.args = args
287 self.keywords = keywords
288
289 def __repr__(self):
290 args = ", ".join(map(repr, self.args))
291 keywords = ", ".join("{}={!r}".format(k, v)
292 for k, v in self.keywords.items())
293 format_string = "{module}.{cls}({func}, {args}, {keywords})"
294 return format_string.format(module=self.__class__.__module__,
Serhiy Storchaka521e5862014-07-22 15:00:37 +0300295 cls=self.__class__.__qualname__,
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000296 func=self.func,
297 args=args,
298 keywords=keywords)
299
300 def _make_unbound_method(self):
301 def _method(*args, **keywords):
302 call_keywords = self.keywords.copy()
303 call_keywords.update(keywords)
304 cls_or_self, *rest = args
305 call_args = (cls_or_self,) + self.args + tuple(rest)
306 return self.func(*call_args, **call_keywords)
307 _method.__isabstractmethod__ = self.__isabstractmethod__
Yury Selivanovda5fe4f2014-01-27 17:28:37 -0500308 _method._partialmethod = self
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000309 return _method
310
311 def __get__(self, obj, cls):
312 get = getattr(self.func, "__get__", None)
313 result = None
314 if get is not None:
315 new_func = get(obj, cls)
316 if new_func is not self.func:
317 # Assume __get__ returning something new indicates the
318 # creation of an appropriate callable
319 result = partial(new_func, *self.args, **self.keywords)
320 try:
321 result.__self__ = new_func.__self__
322 except AttributeError:
323 pass
324 if result is None:
325 # If the underlying descriptor didn't do anything, treat this
326 # like an instance method
327 result = self._make_unbound_method().__get__(obj, cls)
328 return result
329
330 @property
331 def __isabstractmethod__(self):
332 return getattr(self.func, "__isabstractmethod__", False)
333
Antoine Pitroub5b37142012-11-13 21:35:40 +0100334
335################################################################################
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700336### LRU Cache function decorator
337################################################################################
338
Raymond Hettingerdce583e2012-03-16 22:12:20 -0700339_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
Nick Coghlan234515a2010-11-30 06:19:46 +0000340
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700341class _HashedSeq(list):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700342 """ This class guarantees that hash() will be called no more than once
343 per element. This is important because the lru_cache() will hash
344 the key multiple times on a cache miss.
345
346 """
347
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700348 __slots__ = 'hashvalue'
349
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700350 def __init__(self, tup, hash=hash):
351 self[:] = tup
352 self.hashvalue = hash(tup)
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700353
354 def __hash__(self):
355 return self.hashvalue
356
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700357def _make_key(args, kwds, typed,
358 kwd_mark = (object(),),
359 fasttypes = {int, str, frozenset, type(None)},
360 sorted=sorted, tuple=tuple, type=type, len=len):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700361 """Make a cache key from optionally typed positional and keyword arguments
362
363 The key is constructed in a way that is flat as possible rather than
364 as a nested structure that would take more memory.
365
366 If there is only a single argument and its data type is known to cache
367 its hash value, then that argument is returned without a wrapper. This
368 saves space and improves lookup speed.
369
370 """
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700371 key = args
372 if kwds:
373 sorted_items = sorted(kwds.items())
374 key += kwd_mark
375 for item in sorted_items:
376 key += item
377 if typed:
378 key += tuple(type(v) for v in args)
379 if kwds:
380 key += tuple(type(v) for k, v in sorted_items)
381 elif len(key) == 1 and type(key[0]) in fasttypes:
382 return key[0]
383 return _HashedSeq(key)
384
Raymond Hettinger010ce322012-05-19 21:20:48 -0700385def lru_cache(maxsize=128, typed=False):
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000386 """Least-recently-used cache decorator.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000387
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000388 If *maxsize* is set to None, the LRU features are disabled and the cache
389 can grow without bound.
390
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700391 If *typed* is True, arguments of different types will be cached separately.
392 For example, f(3.0) and f(3) will be treated as distinct calls with
393 distinct results.
394
Georg Brandl2e7346a2010-07-31 18:09:23 +0000395 Arguments to the cached function must be hashable.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000396
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700397 View the cache statistics named tuple (hits, misses, maxsize, currsize)
398 with f.cache_info(). Clear the cache and statistics with f.cache_clear().
Raymond Hettinger00f2f972010-12-01 00:47:56 +0000399 Access the underlying function with f.__wrapped__.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000400
401 See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
Georg Brandl2e7346a2010-07-31 18:09:23 +0000402
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000403 """
Raymond Hettinger1ff50df2012-03-30 13:15:48 -0700404
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000405 # Users should only access the lru_cache through its public API:
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000406 # cache_info, cache_clear, and f.__wrapped__
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000407 # The internals of the lru_cache are encapsulated for thread safety and
408 # to allow the implementation to change (including a possible C version).
409
Raymond Hettinger4d588972014-08-12 12:44:52 -0700410 # Early detection of an erroneous call to @lru_cache without any arguments
411 # resulting in the inner function being passed to maxsize instead of an
412 # integer or None.
413 if maxsize is not None and not isinstance(maxsize, int):
414 raise TypeError('Expected maxsize to be an integer or None')
415
Raymond Hettinger9f0ab9f2012-04-29 14:55:27 -0700416 # Constants shared by all lru cache instances:
Raymond Hettingerb6b98c02012-04-29 18:09:02 -0700417 sentinel = object() # unique object used to signal cache misses
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700418 make_key = _make_key # build a key from the function arguments
Raymond Hettinger9f0ab9f2012-04-29 14:55:27 -0700419 PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
420
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700421 def decorating_function(user_function):
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700422 cache = {}
Raymond Hettinger832edde2013-02-17 00:08:45 -0800423 hits = misses = 0
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700424 full = False
Raymond Hettingerc6897852012-03-31 02:19:06 -0700425 cache_get = cache.get # bound method to lookup a key or return None
Raymond Hettingerfd541172013-03-01 03:47:57 -0800426 lock = RLock() # because linkedlist updates aren't threadsafe
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700427 root = [] # root of the circular doubly linked list
428 root[:] = [root, root, None, None] # initialize by pointing to self
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700429
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700430 if maxsize == 0:
431
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700432 def wrapper(*args, **kwds):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700433 # No caching -- just a statistics update after a successful call
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700434 nonlocal misses
Raymond Hettinger7dabfed2012-03-17 15:11:09 -0700435 result = user_function(*args, **kwds)
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700436 misses += 1
437 return result
438
439 elif maxsize is None:
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700440
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000441 def wrapper(*args, **kwds):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700442 # Simple caching without ordering or size limit
Raymond Hettinger832edde2013-02-17 00:08:45 -0800443 nonlocal hits, misses
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700444 key = make_key(args, kwds, typed)
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700445 result = cache_get(key, sentinel)
446 if result is not sentinel:
Nick Coghlan234515a2010-11-30 06:19:46 +0000447 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700448 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700449 result = user_function(*args, **kwds)
450 cache[key] = result
451 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000452 return result
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700453
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000454 else:
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700455
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000456 def wrapper(*args, **kwds):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700457 # Size limited caching that tracks accesses by recency
Raymond Hettinger832edde2013-02-17 00:08:45 -0800458 nonlocal root, hits, misses, full
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700459 key = make_key(args, kwds, typed)
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700460 with lock:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700461 link = cache_get(key)
462 if link is not None:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700463 # Move the link to the front of the circular queue
464 link_prev, link_next, _key, result = link
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700465 link_prev[NEXT] = link_next
466 link_next[PREV] = link_prev
467 last = root[PREV]
468 last[NEXT] = root[PREV] = link
469 link[PREV] = last
470 link[NEXT] = root
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000471 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700472 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700473 result = user_function(*args, **kwds)
474 with lock:
Raymond Hettinger34d94a22012-04-30 14:14:28 -0700475 if key in cache:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700476 # Getting here means that this same key was added to the
477 # cache while the lock was released. Since the link
Raymond Hettinger34d94a22012-04-30 14:14:28 -0700478 # update is already done, we need only return the
479 # computed result and update the count of misses.
480 pass
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700481 elif full:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700482 # Use the old root to store the new key and result.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500483 oldroot = root
484 oldroot[KEY] = key
485 oldroot[RESULT] = result
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700486 # Empty the oldest link and make it the new root.
487 # Keep a reference to the old key and old result to
488 # prevent their ref counts from going to zero during the
489 # update. That will prevent potentially arbitrary object
490 # clean-up code (i.e. __del__) from running while we're
491 # still adjusting the links.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500492 root = oldroot[NEXT]
493 oldkey = root[KEY]
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700494 oldresult = root[RESULT]
Raymond Hettingerc6897852012-03-31 02:19:06 -0700495 root[KEY] = root[RESULT] = None
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700496 # Now update the cache dictionary.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500497 del cache[oldkey]
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700498 # Save the potentially reentrant cache[key] assignment
499 # for last, after the root and links have been put in
500 # a consistent state.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500501 cache[key] = oldroot
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700502 else:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700503 # Put result in a new link at the front of the queue.
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700504 last = root[PREV]
505 link = [last, root, key, result]
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500506 last[NEXT] = root[PREV] = cache[key] = link
Raymond Hettingerbb5f4802013-03-04 04:20:46 -0500507 full = (len(cache) >= maxsize)
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700508 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000509 return result
Georg Brandl2e7346a2010-07-31 18:09:23 +0000510
Nick Coghlan234515a2010-11-30 06:19:46 +0000511 def cache_info():
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000512 """Report cache statistics"""
Nick Coghlan234515a2010-11-30 06:19:46 +0000513 with lock:
Raymond Hettinger832edde2013-02-17 00:08:45 -0800514 return _CacheInfo(hits, misses, maxsize, len(cache))
Nick Coghlan234515a2010-11-30 06:19:46 +0000515
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000516 def cache_clear():
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000517 """Clear the cache and cache statistics"""
Raymond Hettinger832edde2013-02-17 00:08:45 -0800518 nonlocal hits, misses, full
Raymond Hettingercbe88132010-08-14 22:22:10 +0000519 with lock:
520 cache.clear()
Benjamin Peterson954cf572012-03-16 18:22:26 -0500521 root[:] = [root, root, None, None]
Raymond Hettinger832edde2013-02-17 00:08:45 -0800522 hits = misses = 0
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700523 full = False
Georg Brandl2e7346a2010-07-31 18:09:23 +0000524
Nick Coghlan234515a2010-11-30 06:19:46 +0000525 wrapper.cache_info = cache_info
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000526 wrapper.cache_clear = cache_clear
Raymond Hettinger1ff50df2012-03-30 13:15:48 -0700527 return update_wrapper(wrapper, user_function)
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000528
Georg Brandl2e7346a2010-07-31 18:09:23 +0000529 return decorating_function
Łukasz Langa6f692512013-06-05 12:20:24 +0200530
531
532################################################################################
533### singledispatch() - single-dispatch generic function decorator
534################################################################################
535
Łukasz Langa3720c772013-07-01 16:00:38 +0200536def _c3_merge(sequences):
537 """Merges MROs in *sequences* to a single MRO using the C3 algorithm.
538
539 Adapted from http://www.python.org/download/releases/2.3/mro/.
540
541 """
542 result = []
543 while True:
544 sequences = [s for s in sequences if s] # purge empty sequences
545 if not sequences:
546 return result
547 for s1 in sequences: # find merge candidates among seq heads
548 candidate = s1[0]
549 for s2 in sequences:
550 if candidate in s2[1:]:
551 candidate = None
552 break # reject the current head, it appears later
553 else:
554 break
555 if not candidate:
556 raise RuntimeError("Inconsistent hierarchy")
557 result.append(candidate)
558 # remove the chosen candidate
559 for seq in sequences:
560 if seq[0] == candidate:
561 del seq[0]
562
563def _c3_mro(cls, abcs=None):
564 """Computes the method resolution order using extended C3 linearization.
565
566 If no *abcs* are given, the algorithm works exactly like the built-in C3
567 linearization used for method resolution.
568
569 If given, *abcs* is a list of abstract base classes that should be inserted
570 into the resulting MRO. Unrelated ABCs are ignored and don't end up in the
571 result. The algorithm inserts ABCs where their functionality is introduced,
572 i.e. issubclass(cls, abc) returns True for the class itself but returns
573 False for all its direct base classes. Implicit ABCs for a given class
574 (either registered or inferred from the presence of a special method like
575 __len__) are inserted directly after the last ABC explicitly listed in the
576 MRO of said class. If two implicit ABCs end up next to each other in the
577 resulting MRO, their ordering depends on the order of types in *abcs*.
578
579 """
580 for i, base in enumerate(reversed(cls.__bases__)):
581 if hasattr(base, '__abstractmethods__'):
582 boundary = len(cls.__bases__) - i
583 break # Bases up to the last explicit ABC are considered first.
584 else:
585 boundary = 0
586 abcs = list(abcs) if abcs else []
587 explicit_bases = list(cls.__bases__[:boundary])
588 abstract_bases = []
589 other_bases = list(cls.__bases__[boundary:])
590 for base in abcs:
591 if issubclass(cls, base) and not any(
592 issubclass(b, base) for b in cls.__bases__
593 ):
594 # If *cls* is the class that introduces behaviour described by
595 # an ABC *base*, insert said ABC to its MRO.
596 abstract_bases.append(base)
597 for base in abstract_bases:
598 abcs.remove(base)
599 explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases]
600 abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases]
601 other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases]
602 return _c3_merge(
603 [[cls]] +
604 explicit_c3_mros + abstract_c3_mros + other_c3_mros +
605 [explicit_bases] + [abstract_bases] + [other_bases]
606 )
607
608def _compose_mro(cls, types):
609 """Calculates the method resolution order for a given class *cls*.
610
611 Includes relevant abstract base classes (with their respective bases) from
612 the *types* iterable. Uses a modified C3 linearization algorithm.
Łukasz Langa6f692512013-06-05 12:20:24 +0200613
614 """
615 bases = set(cls.__mro__)
Łukasz Langa3720c772013-07-01 16:00:38 +0200616 # Remove entries which are already present in the __mro__ or unrelated.
617 def is_related(typ):
618 return (typ not in bases and hasattr(typ, '__mro__')
619 and issubclass(cls, typ))
620 types = [n for n in types if is_related(n)]
621 # Remove entries which are strict bases of other entries (they will end up
622 # in the MRO anyway.
623 def is_strict_base(typ):
624 for other in types:
625 if typ != other and typ in other.__mro__:
626 return True
627 return False
628 types = [n for n in types if not is_strict_base(n)]
629 # Subclasses of the ABCs in *types* which are also implemented by
630 # *cls* can be used to stabilize ABC ordering.
631 type_set = set(types)
632 mro = []
633 for typ in types:
634 found = []
635 for sub in typ.__subclasses__():
636 if sub not in bases and issubclass(cls, sub):
637 found.append([s for s in sub.__mro__ if s in type_set])
638 if not found:
639 mro.append(typ)
640 continue
641 # Favor subclasses with the biggest number of useful bases
642 found.sort(key=len, reverse=True)
643 for sub in found:
644 for subcls in sub:
645 if subcls not in mro:
646 mro.append(subcls)
647 return _c3_mro(cls, abcs=mro)
Łukasz Langa6f692512013-06-05 12:20:24 +0200648
649def _find_impl(cls, registry):
Łukasz Langa3720c772013-07-01 16:00:38 +0200650 """Returns the best matching implementation from *registry* for type *cls*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200651
Łukasz Langa3720c772013-07-01 16:00:38 +0200652 Where there is no registered implementation for a specific type, its method
653 resolution order is used to find a more generic implementation.
654
655 Note: if *registry* does not contain an implementation for the base
656 *object* type, this function may return None.
Łukasz Langa6f692512013-06-05 12:20:24 +0200657
658 """
659 mro = _compose_mro(cls, registry.keys())
660 match = None
661 for t in mro:
662 if match is not None:
Łukasz Langa3720c772013-07-01 16:00:38 +0200663 # If *match* is an implicit ABC but there is another unrelated,
664 # equally matching implicit ABC, refuse the temptation to guess.
665 if (t in registry and t not in cls.__mro__
666 and match not in cls.__mro__
667 and not issubclass(match, t)):
Łukasz Langa6f692512013-06-05 12:20:24 +0200668 raise RuntimeError("Ambiguous dispatch: {} or {}".format(
669 match, t))
670 break
671 if t in registry:
672 match = t
673 return registry.get(match)
674
675def singledispatch(func):
676 """Single-dispatch generic function decorator.
677
678 Transforms a function into a generic function, which can have different
679 behaviours depending upon the type of its first argument. The decorated
680 function acts as the default implementation, and additional
Łukasz Langa3720c772013-07-01 16:00:38 +0200681 implementations can be registered using the register() attribute of the
682 generic function.
Łukasz Langa6f692512013-06-05 12:20:24 +0200683
684 """
685 registry = {}
686 dispatch_cache = WeakKeyDictionary()
687 cache_token = None
688
Łukasz Langa3720c772013-07-01 16:00:38 +0200689 def dispatch(cls):
690 """generic_func.dispatch(cls) -> <function implementation>
Łukasz Langa6f692512013-06-05 12:20:24 +0200691
692 Runs the dispatch algorithm to return the best available implementation
Łukasz Langa3720c772013-07-01 16:00:38 +0200693 for the given *cls* registered on *generic_func*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200694
695 """
696 nonlocal cache_token
697 if cache_token is not None:
698 current_token = get_cache_token()
699 if cache_token != current_token:
700 dispatch_cache.clear()
701 cache_token = current_token
702 try:
Łukasz Langa3720c772013-07-01 16:00:38 +0200703 impl = dispatch_cache[cls]
Łukasz Langa6f692512013-06-05 12:20:24 +0200704 except KeyError:
705 try:
Łukasz Langa3720c772013-07-01 16:00:38 +0200706 impl = registry[cls]
Łukasz Langa6f692512013-06-05 12:20:24 +0200707 except KeyError:
Łukasz Langa3720c772013-07-01 16:00:38 +0200708 impl = _find_impl(cls, registry)
709 dispatch_cache[cls] = impl
Łukasz Langa6f692512013-06-05 12:20:24 +0200710 return impl
711
Łukasz Langa3720c772013-07-01 16:00:38 +0200712 def register(cls, func=None):
713 """generic_func.register(cls, func) -> func
Łukasz Langa6f692512013-06-05 12:20:24 +0200714
Łukasz Langa3720c772013-07-01 16:00:38 +0200715 Registers a new implementation for the given *cls* on a *generic_func*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200716
717 """
718 nonlocal cache_token
719 if func is None:
Łukasz Langa3720c772013-07-01 16:00:38 +0200720 return lambda f: register(cls, f)
721 registry[cls] = func
722 if cache_token is None and hasattr(cls, '__abstractmethods__'):
Łukasz Langa6f692512013-06-05 12:20:24 +0200723 cache_token = get_cache_token()
724 dispatch_cache.clear()
725 return func
726
727 def wrapper(*args, **kw):
728 return dispatch(args[0].__class__)(*args, **kw)
729
730 registry[object] = func
731 wrapper.register = register
732 wrapper.dispatch = dispatch
733 wrapper.registry = MappingProxyType(registry)
734 wrapper._clear_cache = dispatch_cache.clear
735 update_wrapper(wrapper, func)
736 return wrapper