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