blob: 24fdb166ab1ac531ceb837ede9f274d9f273e8dc [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
Nick Coghlanf05d9812013-10-02 00:02:03 +100092# The correct way to indicate that a comparison operation doesn't
93# recognise the other type is to return NotImplemented and let the
94# interpreter handle raising TypeError if both operands return
95# NotImplemented from their respective comparison methods
96#
97# This makes the implementation of total_ordering more complicated, since
98# we need to be careful not to trigger infinite recursion when two
99# different types that both use this decorator encounter each other.
100#
101# For example, if a type implements __lt__, it's natural to define
102# __gt__ as something like:
103#
104# lambda self, other: not self < other and not self == other
105#
106# However, using the operator syntax like that ends up invoking the full
107# type checking machinery again and means we can end up bouncing back and
108# forth between the two operands until we run out of stack space.
109#
110# The solution is to define helper functions that invoke the appropriate
111# magic methods directly, ensuring we only try each operand once, and
112# return NotImplemented immediately if it is returned from the
113# underlying user provided method. Using this scheme, the __gt__ derived
114# from a user provided __lt__ becomes:
115#
116# lambda self, other: _not_op_and_not_eq(self.__lt__, self, other))
117
118def _not_op(op, other):
119 # "not a < b" handles "a >= b"
120 # "not a <= b" handles "a > b"
121 # "not a >= b" handles "a < b"
122 # "not a > b" handles "a <= b"
123 op_result = op(other)
124 if op_result is NotImplemented:
125 return NotImplemented
126 return not op_result
127
128def _op_or_eq(op, self, other):
129 # "a < b or a == b" handles "a <= b"
130 # "a > b or a == b" handles "a >= b"
131 op_result = op(other)
132 if op_result is NotImplemented:
133 return NotImplemented
134 return op_result or self == other
135
136def _not_op_and_not_eq(op, self, other):
137 # "not (a < b or a == b)" handles "a > b"
138 # "not a < b and a != b" is equivalent
139 # "not (a > b or a == b)" handles "a < b"
140 # "not a > b and a != b" is equivalent
141 op_result = op(other)
142 if op_result is NotImplemented:
143 return NotImplemented
144 return not op_result and self != other
145
146def _not_op_or_eq(op, self, other):
147 # "not a <= b or a == b" handles "a >= b"
148 # "not a >= b or a == b" handles "a <= b"
149 op_result = op(other)
150 if op_result is NotImplemented:
151 return NotImplemented
152 return not op_result or self == other
153
154def _op_and_not_eq(op, self, other):
155 # "a <= b and not a == b" handles "a < b"
156 # "a >= b and not a == b" handles "a > b"
157 op_result = op(other)
158 if op_result is NotImplemented:
159 return NotImplemented
160 return op_result and self != other
161
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000162def total_ordering(cls):
Georg Brandle5a26732010-05-19 21:06:36 +0000163 """Class decorator that fills in missing ordering methods"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000164 convert = {
Nick Coghlanf05d9812013-10-02 00:02:03 +1000165 '__lt__': [('__gt__', lambda self, other: _not_op_and_not_eq(self.__lt__, self, other)),
166 ('__le__', lambda self, other: _op_or_eq(self.__lt__, self, other)),
167 ('__ge__', lambda self, other: _not_op(self.__lt__, other))],
168 '__le__': [('__ge__', lambda self, other: _not_op_or_eq(self.__le__, self, other)),
169 ('__lt__', lambda self, other: _op_and_not_eq(self.__le__, self, other)),
170 ('__gt__', lambda self, other: _not_op(self.__le__, other))],
171 '__gt__': [('__lt__', lambda self, other: _not_op_and_not_eq(self.__gt__, self, other)),
172 ('__ge__', lambda self, other: _op_or_eq(self.__gt__, self, other)),
173 ('__le__', lambda self, other: _not_op(self.__gt__, other))],
174 '__ge__': [('__le__', lambda self, other: _not_op_or_eq(self.__ge__, self, other)),
175 ('__gt__', lambda self, other: _op_and_not_eq(self.__ge__, self, other)),
176 ('__lt__', lambda self, other: _not_op(self.__ge__, other))]
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000177 }
Raymond Hettinger3255c632010-09-16 00:31:21 +0000178 # Find user-defined comparisons (not those inherited from object).
Raymond Hettinger1006bd42010-09-14 22:55:13 +0000179 roots = [op for op in convert if getattr(cls, op, None) is not getattr(object, op, None)]
Raymond Hettinger56de7e22010-04-10 16:59:03 +0000180 if not roots:
181 raise ValueError('must define at least one ordering operation: < > <= >=')
182 root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000183 for opname, opfunc in convert[root]:
184 if opname not in roots:
185 opfunc.__name__ = opname
186 opfunc.__doc__ = getattr(int, opname).__doc__
187 setattr(cls, opname, opfunc)
188 return cls
189
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700190
191################################################################################
192### cmp_to_key() function converter
193################################################################################
194
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000195def cmp_to_key(mycmp):
Georg Brandle5a26732010-05-19 21:06:36 +0000196 """Convert a cmp= function into a key= function"""
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000197 class K(object):
Raymond Hettingera0d1d962011-03-21 17:50:28 -0700198 __slots__ = ['obj']
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700199 def __init__(self, obj):
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000200 self.obj = obj
201 def __lt__(self, other):
202 return mycmp(self.obj, other.obj) < 0
203 def __gt__(self, other):
204 return mycmp(self.obj, other.obj) > 0
205 def __eq__(self, other):
206 return mycmp(self.obj, other.obj) == 0
207 def __le__(self, other):
208 return mycmp(self.obj, other.obj) <= 0
209 def __ge__(self, other):
210 return mycmp(self.obj, other.obj) >= 0
211 def __ne__(self, other):
212 return mycmp(self.obj, other.obj) != 0
Raymond Hettinger003be522011-05-03 11:01:32 -0700213 __hash__ = None
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000214 return K
Georg Brandl2e7346a2010-07-31 18:09:23 +0000215
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700216try:
217 from _functools import cmp_to_key
Brett Cannoncd171c82013-07-04 17:43:24 -0400218except ImportError:
Raymond Hettinger7ab9e222011-04-05 02:33:54 -0700219 pass
220
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700221
222################################################################################
Antoine Pitroub5b37142012-11-13 21:35:40 +0100223### partial() argument application
224################################################################################
225
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000226# Purely functional, no descriptor behaviour
Antoine Pitroub5b37142012-11-13 21:35:40 +0100227def partial(func, *args, **keywords):
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000228 """New function with partial application of the given arguments
Antoine Pitroub5b37142012-11-13 21:35:40 +0100229 and keywords.
230 """
231 def newfunc(*fargs, **fkeywords):
232 newkeywords = keywords.copy()
233 newkeywords.update(fkeywords)
234 return func(*(args + fargs), **newkeywords)
235 newfunc.func = func
236 newfunc.args = args
237 newfunc.keywords = keywords
238 return newfunc
239
240try:
241 from _functools import partial
Brett Cannoncd171c82013-07-04 17:43:24 -0400242except ImportError:
Antoine Pitroub5b37142012-11-13 21:35:40 +0100243 pass
244
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000245# Descriptor version
246class partialmethod(object):
247 """Method descriptor with partial application of the given arguments
248 and keywords.
249
250 Supports wrapping existing descriptors and handles non-descriptor
251 callables as instance methods.
252 """
253
254 def __init__(self, func, *args, **keywords):
255 if not callable(func) and not hasattr(func, "__get__"):
256 raise TypeError("{!r} is not callable or a descriptor"
257 .format(func))
258
259 # func could be a descriptor like classmethod which isn't callable,
260 # so we can't inherit from partial (it verifies func is callable)
261 if isinstance(func, partialmethod):
262 # flattening is mandatory in order to place cls/self before all
263 # other arguments
264 # it's also more efficient since only one function will be called
265 self.func = func.func
266 self.args = func.args + args
267 self.keywords = func.keywords.copy()
268 self.keywords.update(keywords)
269 else:
270 self.func = func
271 self.args = args
272 self.keywords = keywords
273
274 def __repr__(self):
275 args = ", ".join(map(repr, self.args))
276 keywords = ", ".join("{}={!r}".format(k, v)
277 for k, v in self.keywords.items())
278 format_string = "{module}.{cls}({func}, {args}, {keywords})"
279 return format_string.format(module=self.__class__.__module__,
280 cls=self.__class__.__name__,
281 func=self.func,
282 args=args,
283 keywords=keywords)
284
285 def _make_unbound_method(self):
286 def _method(*args, **keywords):
287 call_keywords = self.keywords.copy()
288 call_keywords.update(keywords)
289 cls_or_self, *rest = args
290 call_args = (cls_or_self,) + self.args + tuple(rest)
291 return self.func(*call_args, **call_keywords)
292 _method.__isabstractmethod__ = self.__isabstractmethod__
Yury Selivanovda5fe4f2014-01-27 17:28:37 -0500293 _method._partialmethod = self
Nick Coghlanf4cb48a2013-11-03 16:41:46 +1000294 return _method
295
296 def __get__(self, obj, cls):
297 get = getattr(self.func, "__get__", None)
298 result = None
299 if get is not None:
300 new_func = get(obj, cls)
301 if new_func is not self.func:
302 # Assume __get__ returning something new indicates the
303 # creation of an appropriate callable
304 result = partial(new_func, *self.args, **self.keywords)
305 try:
306 result.__self__ = new_func.__self__
307 except AttributeError:
308 pass
309 if result is None:
310 # If the underlying descriptor didn't do anything, treat this
311 # like an instance method
312 result = self._make_unbound_method().__get__(obj, cls)
313 return result
314
315 @property
316 def __isabstractmethod__(self):
317 return getattr(self.func, "__isabstractmethod__", False)
318
Antoine Pitroub5b37142012-11-13 21:35:40 +0100319
320################################################################################
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700321### LRU Cache function decorator
322################################################################################
323
Raymond Hettingerdce583e2012-03-16 22:12:20 -0700324_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
Nick Coghlan234515a2010-11-30 06:19:46 +0000325
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700326class _HashedSeq(list):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700327 """ This class guarantees that hash() will be called no more than once
328 per element. This is important because the lru_cache() will hash
329 the key multiple times on a cache miss.
330
331 """
332
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700333 __slots__ = 'hashvalue'
334
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700335 def __init__(self, tup, hash=hash):
336 self[:] = tup
337 self.hashvalue = hash(tup)
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700338
339 def __hash__(self):
340 return self.hashvalue
341
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700342def _make_key(args, kwds, typed,
343 kwd_mark = (object(),),
344 fasttypes = {int, str, frozenset, type(None)},
345 sorted=sorted, tuple=tuple, type=type, len=len):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700346 """Make a cache key from optionally typed positional and keyword arguments
347
348 The key is constructed in a way that is flat as possible rather than
349 as a nested structure that would take more memory.
350
351 If there is only a single argument and its data type is known to cache
352 its hash value, then that argument is returned without a wrapper. This
353 saves space and improves lookup speed.
354
355 """
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700356 key = args
357 if kwds:
358 sorted_items = sorted(kwds.items())
359 key += kwd_mark
360 for item in sorted_items:
361 key += item
362 if typed:
363 key += tuple(type(v) for v in args)
364 if kwds:
365 key += tuple(type(v) for k, v in sorted_items)
366 elif len(key) == 1 and type(key[0]) in fasttypes:
367 return key[0]
368 return _HashedSeq(key)
369
Raymond Hettinger010ce322012-05-19 21:20:48 -0700370def lru_cache(maxsize=128, typed=False):
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000371 """Least-recently-used cache decorator.
Georg Brandl2e7346a2010-07-31 18:09:23 +0000372
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000373 If *maxsize* is set to None, the LRU features are disabled and the cache
374 can grow without bound.
375
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700376 If *typed* is True, arguments of different types will be cached separately.
377 For example, f(3.0) and f(3) will be treated as distinct calls with
378 distinct results.
379
Georg Brandl2e7346a2010-07-31 18:09:23 +0000380 Arguments to the cached function must be hashable.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000381
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700382 View the cache statistics named tuple (hits, misses, maxsize, currsize)
383 with f.cache_info(). Clear the cache and statistics with f.cache_clear().
Raymond Hettinger00f2f972010-12-01 00:47:56 +0000384 Access the underlying function with f.__wrapped__.
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000385
386 See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
Georg Brandl2e7346a2010-07-31 18:09:23 +0000387
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000388 """
Raymond Hettinger1ff50df2012-03-30 13:15:48 -0700389
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000390 # Users should only access the lru_cache through its public API:
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000391 # cache_info, cache_clear, and f.__wrapped__
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000392 # The internals of the lru_cache are encapsulated for thread safety and
393 # to allow the implementation to change (including a possible C version).
394
Raymond Hettinger4d588972014-08-12 12:44:52 -0700395 # Early detection of an erroneous call to @lru_cache without any arguments
396 # resulting in the inner function being passed to maxsize instead of an
397 # integer or None.
398 if maxsize is not None and not isinstance(maxsize, int):
399 raise TypeError('Expected maxsize to be an integer or None')
400
Raymond Hettinger9f0ab9f2012-04-29 14:55:27 -0700401 # Constants shared by all lru cache instances:
Raymond Hettingerb6b98c02012-04-29 18:09:02 -0700402 sentinel = object() # unique object used to signal cache misses
Raymond Hettinger0c9050c2012-06-04 00:21:14 -0700403 make_key = _make_key # build a key from the function arguments
Raymond Hettinger9f0ab9f2012-04-29 14:55:27 -0700404 PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
405
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700406 def decorating_function(user_function):
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700407 cache = {}
Raymond Hettinger832edde2013-02-17 00:08:45 -0800408 hits = misses = 0
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700409 full = False
Raymond Hettingerc6897852012-03-31 02:19:06 -0700410 cache_get = cache.get # bound method to lookup a key or return None
Raymond Hettingerfd541172013-03-01 03:47:57 -0800411 lock = RLock() # because linkedlist updates aren't threadsafe
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700412 root = [] # root of the circular doubly linked list
413 root[:] = [root, root, None, None] # initialize by pointing to self
Raymond Hettinger6e8c8172012-03-16 16:53:05 -0700414
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700415 if maxsize == 0:
416
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700417 def wrapper(*args, **kwds):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700418 # No caching -- just a statistics update after a successful call
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700419 nonlocal misses
Raymond Hettinger7dabfed2012-03-17 15:11:09 -0700420 result = user_function(*args, **kwds)
Raymond Hettinger7e0c5812012-03-17 15:10:24 -0700421 misses += 1
422 return result
423
424 elif maxsize is None:
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700425
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000426 def wrapper(*args, **kwds):
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700427 # Simple caching without ordering or size limit
Raymond Hettinger832edde2013-02-17 00:08:45 -0800428 nonlocal hits, misses
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700429 key = make_key(args, kwds, typed)
Raymond Hettinger7f7a5a72012-03-30 21:50:40 -0700430 result = cache_get(key, sentinel)
431 if result is not sentinel:
Nick Coghlan234515a2010-11-30 06:19:46 +0000432 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700433 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700434 result = user_function(*args, **kwds)
435 cache[key] = result
436 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000437 return result
Raymond Hettingerbc8e81d2012-03-17 00:24:09 -0700438
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000439 else:
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 # Size limited caching that tracks accesses by recency
Raymond Hettinger832edde2013-02-17 00:08:45 -0800443 nonlocal root, hits, misses, full
Raymond Hettinger9acbb602012-04-30 22:32:16 -0700444 key = make_key(args, kwds, typed)
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700445 with lock:
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700446 link = cache_get(key)
447 if link is not None:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700448 # Move the link to the front of the circular queue
449 link_prev, link_next, _key, result = link
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700450 link_prev[NEXT] = link_next
451 link_next[PREV] = link_prev
452 last = root[PREV]
453 last[NEXT] = root[PREV] = link
454 link[PREV] = last
455 link[NEXT] = root
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000456 hits += 1
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700457 return result
Raymond Hettinger4b779b32011-10-15 23:50:42 -0700458 result = user_function(*args, **kwds)
459 with lock:
Raymond Hettinger34d94a22012-04-30 14:14:28 -0700460 if key in cache:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700461 # Getting here means that this same key was added to the
462 # cache while the lock was released. Since the link
Raymond Hettinger34d94a22012-04-30 14:14:28 -0700463 # update is already done, we need only return the
464 # computed result and update the count of misses.
465 pass
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700466 elif full:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700467 # Use the old root to store the new key and result.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500468 oldroot = root
469 oldroot[KEY] = key
470 oldroot[RESULT] = result
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700471 # Empty the oldest link and make it the new root.
472 # Keep a reference to the old key and old result to
473 # prevent their ref counts from going to zero during the
474 # update. That will prevent potentially arbitrary object
475 # clean-up code (i.e. __del__) from running while we're
476 # still adjusting the links.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500477 root = oldroot[NEXT]
478 oldkey = root[KEY]
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700479 oldresult = root[RESULT]
Raymond Hettingerc6897852012-03-31 02:19:06 -0700480 root[KEY] = root[RESULT] = None
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700481 # Now update the cache dictionary.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500482 del cache[oldkey]
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700483 # Save the potentially reentrant cache[key] assignment
484 # for last, after the root and links have been put in
485 # a consistent state.
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500486 cache[key] = oldroot
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700487 else:
Raymond Hettingerf96b2b02013-03-08 21:11:55 -0700488 # Put result in a new link at the front of the queue.
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700489 last = root[PREV]
490 link = [last, root, key, result]
Raymond Hettingerf2c17a92013-03-04 03:34:09 -0500491 last[NEXT] = root[PREV] = cache[key] = link
Raymond Hettingerbb5f4802013-03-04 04:20:46 -0500492 full = (len(cache) >= maxsize)
Raymond Hettingerec0e9102012-03-16 01:16:31 -0700493 misses += 1
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +0000494 return result
Georg Brandl2e7346a2010-07-31 18:09:23 +0000495
Nick Coghlan234515a2010-11-30 06:19:46 +0000496 def cache_info():
Raymond Hettinger5e20bab2010-11-30 07:13:04 +0000497 """Report cache statistics"""
Nick Coghlan234515a2010-11-30 06:19:46 +0000498 with lock:
Raymond Hettinger832edde2013-02-17 00:08:45 -0800499 return _CacheInfo(hits, misses, maxsize, len(cache))
Nick Coghlan234515a2010-11-30 06:19:46 +0000500
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000501 def cache_clear():
Benjamin Peterson1f594ad2010-08-08 13:17:07 +0000502 """Clear the cache and cache statistics"""
Raymond Hettinger832edde2013-02-17 00:08:45 -0800503 nonlocal hits, misses, full
Raymond Hettingercbe88132010-08-14 22:22:10 +0000504 with lock:
505 cache.clear()
Benjamin Peterson954cf572012-03-16 18:22:26 -0500506 root[:] = [root, root, None, None]
Raymond Hettinger832edde2013-02-17 00:08:45 -0800507 hits = misses = 0
Raymond Hettinger018b4fb2012-04-30 20:48:55 -0700508 full = False
Georg Brandl2e7346a2010-07-31 18:09:23 +0000509
Nick Coghlan234515a2010-11-30 06:19:46 +0000510 wrapper.cache_info = cache_info
Raymond Hettinger02566ec2010-09-04 22:46:06 +0000511 wrapper.cache_clear = cache_clear
Raymond Hettinger1ff50df2012-03-30 13:15:48 -0700512 return update_wrapper(wrapper, user_function)
Raymond Hettinger5fa40c02010-11-25 08:11:57 +0000513
Georg Brandl2e7346a2010-07-31 18:09:23 +0000514 return decorating_function
Łukasz Langa6f692512013-06-05 12:20:24 +0200515
516
517################################################################################
518### singledispatch() - single-dispatch generic function decorator
519################################################################################
520
Łukasz Langa3720c772013-07-01 16:00:38 +0200521def _c3_merge(sequences):
522 """Merges MROs in *sequences* to a single MRO using the C3 algorithm.
523
524 Adapted from http://www.python.org/download/releases/2.3/mro/.
525
526 """
527 result = []
528 while True:
529 sequences = [s for s in sequences if s] # purge empty sequences
530 if not sequences:
531 return result
532 for s1 in sequences: # find merge candidates among seq heads
533 candidate = s1[0]
534 for s2 in sequences:
535 if candidate in s2[1:]:
536 candidate = None
537 break # reject the current head, it appears later
538 else:
539 break
540 if not candidate:
541 raise RuntimeError("Inconsistent hierarchy")
542 result.append(candidate)
543 # remove the chosen candidate
544 for seq in sequences:
545 if seq[0] == candidate:
546 del seq[0]
547
548def _c3_mro(cls, abcs=None):
549 """Computes the method resolution order using extended C3 linearization.
550
551 If no *abcs* are given, the algorithm works exactly like the built-in C3
552 linearization used for method resolution.
553
554 If given, *abcs* is a list of abstract base classes that should be inserted
555 into the resulting MRO. Unrelated ABCs are ignored and don't end up in the
556 result. The algorithm inserts ABCs where their functionality is introduced,
557 i.e. issubclass(cls, abc) returns True for the class itself but returns
558 False for all its direct base classes. Implicit ABCs for a given class
559 (either registered or inferred from the presence of a special method like
560 __len__) are inserted directly after the last ABC explicitly listed in the
561 MRO of said class. If two implicit ABCs end up next to each other in the
562 resulting MRO, their ordering depends on the order of types in *abcs*.
563
564 """
565 for i, base in enumerate(reversed(cls.__bases__)):
566 if hasattr(base, '__abstractmethods__'):
567 boundary = len(cls.__bases__) - i
568 break # Bases up to the last explicit ABC are considered first.
569 else:
570 boundary = 0
571 abcs = list(abcs) if abcs else []
572 explicit_bases = list(cls.__bases__[:boundary])
573 abstract_bases = []
574 other_bases = list(cls.__bases__[boundary:])
575 for base in abcs:
576 if issubclass(cls, base) and not any(
577 issubclass(b, base) for b in cls.__bases__
578 ):
579 # If *cls* is the class that introduces behaviour described by
580 # an ABC *base*, insert said ABC to its MRO.
581 abstract_bases.append(base)
582 for base in abstract_bases:
583 abcs.remove(base)
584 explicit_c3_mros = [_c3_mro(base, abcs=abcs) for base in explicit_bases]
585 abstract_c3_mros = [_c3_mro(base, abcs=abcs) for base in abstract_bases]
586 other_c3_mros = [_c3_mro(base, abcs=abcs) for base in other_bases]
587 return _c3_merge(
588 [[cls]] +
589 explicit_c3_mros + abstract_c3_mros + other_c3_mros +
590 [explicit_bases] + [abstract_bases] + [other_bases]
591 )
592
593def _compose_mro(cls, types):
594 """Calculates the method resolution order for a given class *cls*.
595
596 Includes relevant abstract base classes (with their respective bases) from
597 the *types* iterable. Uses a modified C3 linearization algorithm.
Łukasz Langa6f692512013-06-05 12:20:24 +0200598
599 """
600 bases = set(cls.__mro__)
Łukasz Langa3720c772013-07-01 16:00:38 +0200601 # Remove entries which are already present in the __mro__ or unrelated.
602 def is_related(typ):
603 return (typ not in bases and hasattr(typ, '__mro__')
604 and issubclass(cls, typ))
605 types = [n for n in types if is_related(n)]
606 # Remove entries which are strict bases of other entries (they will end up
607 # in the MRO anyway.
608 def is_strict_base(typ):
609 for other in types:
610 if typ != other and typ in other.__mro__:
611 return True
612 return False
613 types = [n for n in types if not is_strict_base(n)]
614 # Subclasses of the ABCs in *types* which are also implemented by
615 # *cls* can be used to stabilize ABC ordering.
616 type_set = set(types)
617 mro = []
618 for typ in types:
619 found = []
620 for sub in typ.__subclasses__():
621 if sub not in bases and issubclass(cls, sub):
622 found.append([s for s in sub.__mro__ if s in type_set])
623 if not found:
624 mro.append(typ)
625 continue
626 # Favor subclasses with the biggest number of useful bases
627 found.sort(key=len, reverse=True)
628 for sub in found:
629 for subcls in sub:
630 if subcls not in mro:
631 mro.append(subcls)
632 return _c3_mro(cls, abcs=mro)
Łukasz Langa6f692512013-06-05 12:20:24 +0200633
634def _find_impl(cls, registry):
Łukasz Langa3720c772013-07-01 16:00:38 +0200635 """Returns the best matching implementation from *registry* for type *cls*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200636
Łukasz Langa3720c772013-07-01 16:00:38 +0200637 Where there is no registered implementation for a specific type, its method
638 resolution order is used to find a more generic implementation.
639
640 Note: if *registry* does not contain an implementation for the base
641 *object* type, this function may return None.
Łukasz Langa6f692512013-06-05 12:20:24 +0200642
643 """
644 mro = _compose_mro(cls, registry.keys())
645 match = None
646 for t in mro:
647 if match is not None:
Łukasz Langa3720c772013-07-01 16:00:38 +0200648 # If *match* is an implicit ABC but there is another unrelated,
649 # equally matching implicit ABC, refuse the temptation to guess.
650 if (t in registry and t not in cls.__mro__
651 and match not in cls.__mro__
652 and not issubclass(match, t)):
Łukasz Langa6f692512013-06-05 12:20:24 +0200653 raise RuntimeError("Ambiguous dispatch: {} or {}".format(
654 match, t))
655 break
656 if t in registry:
657 match = t
658 return registry.get(match)
659
660def singledispatch(func):
661 """Single-dispatch generic function decorator.
662
663 Transforms a function into a generic function, which can have different
664 behaviours depending upon the type of its first argument. The decorated
665 function acts as the default implementation, and additional
Łukasz Langa3720c772013-07-01 16:00:38 +0200666 implementations can be registered using the register() attribute of the
667 generic function.
Łukasz Langa6f692512013-06-05 12:20:24 +0200668
669 """
670 registry = {}
671 dispatch_cache = WeakKeyDictionary()
672 cache_token = None
673
Łukasz Langa3720c772013-07-01 16:00:38 +0200674 def dispatch(cls):
675 """generic_func.dispatch(cls) -> <function implementation>
Łukasz Langa6f692512013-06-05 12:20:24 +0200676
677 Runs the dispatch algorithm to return the best available implementation
Łukasz Langa3720c772013-07-01 16:00:38 +0200678 for the given *cls* registered on *generic_func*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200679
680 """
681 nonlocal cache_token
682 if cache_token is not None:
683 current_token = get_cache_token()
684 if cache_token != current_token:
685 dispatch_cache.clear()
686 cache_token = current_token
687 try:
Łukasz Langa3720c772013-07-01 16:00:38 +0200688 impl = dispatch_cache[cls]
Łukasz Langa6f692512013-06-05 12:20:24 +0200689 except KeyError:
690 try:
Łukasz Langa3720c772013-07-01 16:00:38 +0200691 impl = registry[cls]
Łukasz Langa6f692512013-06-05 12:20:24 +0200692 except KeyError:
Łukasz Langa3720c772013-07-01 16:00:38 +0200693 impl = _find_impl(cls, registry)
694 dispatch_cache[cls] = impl
Łukasz Langa6f692512013-06-05 12:20:24 +0200695 return impl
696
Łukasz Langa3720c772013-07-01 16:00:38 +0200697 def register(cls, func=None):
698 """generic_func.register(cls, func) -> func
Łukasz Langa6f692512013-06-05 12:20:24 +0200699
Łukasz Langa3720c772013-07-01 16:00:38 +0200700 Registers a new implementation for the given *cls* on a *generic_func*.
Łukasz Langa6f692512013-06-05 12:20:24 +0200701
702 """
703 nonlocal cache_token
704 if func is None:
Łukasz Langa3720c772013-07-01 16:00:38 +0200705 return lambda f: register(cls, f)
706 registry[cls] = func
707 if cache_token is None and hasattr(cls, '__abstractmethods__'):
Łukasz Langa6f692512013-06-05 12:20:24 +0200708 cache_token = get_cache_token()
709 dispatch_cache.clear()
710 return func
711
712 def wrapper(*args, **kw):
713 return dispatch(args[0].__class__)(*args, **kw)
714
715 registry[object] = func
716 wrapper.register = register
717 wrapper.dispatch = dispatch
718 wrapper.registry = MappingProxyType(registry)
719 wrapper._clear_cache = dispatch_cache.clear
720 update_wrapper(wrapper, func)
721 return wrapper