functools.py 28 KB

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