functools.py 37 KB

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