Debian Codegraph @

lib-python/3/functools.py

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