functools.py 32 KB

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