functools.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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 an iterable, from left to right.
  207. This effectively reduces the iterable to a single value. If initial is present,
  208. it is placed before the items of the iterable in the calculation, and serves as
  209. a default when the iterable is empty.
  210. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
  211. calculates ((((1 + 2) + 3) + 4) + 5).
  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. __class_getitem__ = classmethod(GenericAlias)
  287. try:
  288. from _functools import partial
  289. except ImportError:
  290. pass
  291. # Descriptor version
  292. class partialmethod(object):
  293. """Method descriptor with partial application of the given arguments
  294. and keywords.
  295. Supports wrapping existing descriptors and handles non-descriptor
  296. callables as instance methods.
  297. """
  298. def __init__(self, func, /, *args, **keywords):
  299. if not callable(func) and not hasattr(func, "__get__"):
  300. raise TypeError("{!r} is not callable or a descriptor"
  301. .format(func))
  302. # func could be a descriptor like classmethod which isn't callable,
  303. # so we can't inherit from partial (it verifies func is callable)
  304. if isinstance(func, partialmethod):
  305. # flattening is mandatory in order to place cls/self before all
  306. # other arguments
  307. # it's also more efficient since only one function will be called
  308. self.func = func.func
  309. self.args = func.args + args
  310. self.keywords = {**func.keywords, **keywords}
  311. else:
  312. self.func = func
  313. self.args = args
  314. self.keywords = keywords
  315. def __repr__(self):
  316. cls = type(self)
  317. module = cls.__module__
  318. qualname = cls.__qualname__
  319. args = [repr(self.func)]
  320. args.extend(map(repr, self.args))
  321. args.extend(f"{k}={v!r}" for k, v in self.keywords.items())
  322. return f"{module}.{qualname}({', '.join(args)})"
  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://docs.python.org/3/howto/mro.html.
  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_union_type(cls):
  714. from typing import get_origin, Union
  715. return get_origin(cls) in {Union, types.UnionType}
  716. def _is_valid_dispatch_type(cls):
  717. if isinstance(cls, type):
  718. return True
  719. from typing import get_args
  720. return (_is_union_type(cls) and
  721. all(isinstance(arg, type) for arg in get_args(cls)))
  722. def register(cls, func=None):
  723. """generic_func.register(cls, func) -> func
  724. Registers a new implementation for the given *cls* on a *generic_func*.
  725. """
  726. nonlocal cache_token
  727. if _is_valid_dispatch_type(cls):
  728. if func is None:
  729. return lambda f: register(cls, f)
  730. else:
  731. if func is not None:
  732. raise TypeError(
  733. f"Invalid first argument to `register()`. "
  734. f"{cls!r} is not a class or union type."
  735. )
  736. ann = getattr(cls, '__annotations__', {})
  737. if not ann:
  738. raise TypeError(
  739. f"Invalid first argument to `register()`: {cls!r}. "
  740. f"Use either `@register(some_class)` or plain `@register` "
  741. f"on an annotated function."
  742. )
  743. func = cls
  744. # only import typing if annotation parsing is necessary
  745. from typing import get_type_hints
  746. argname, cls = next(iter(get_type_hints(func).items()))
  747. if not _is_valid_dispatch_type(cls):
  748. if _is_union_type(cls):
  749. raise TypeError(
  750. f"Invalid annotation for {argname!r}. "
  751. f"{cls!r} not all arguments are classes."
  752. )
  753. else:
  754. raise TypeError(
  755. f"Invalid annotation for {argname!r}. "
  756. f"{cls!r} is not a class."
  757. )
  758. if _is_union_type(cls):
  759. from typing import get_args
  760. for arg in get_args(cls):
  761. registry[arg] = func
  762. else:
  763. registry[cls] = func
  764. if cache_token is None and hasattr(cls, '__abstractmethods__'):
  765. cache_token = get_cache_token()
  766. dispatch_cache.clear()
  767. return func
  768. def wrapper(*args, **kw):
  769. if not args:
  770. raise TypeError(f'{funcname} requires at least '
  771. '1 positional argument')
  772. return dispatch(args[0].__class__)(*args, **kw)
  773. funcname = getattr(func, '__name__', 'singledispatch function')
  774. registry[object] = func
  775. wrapper.register = register
  776. wrapper.dispatch = dispatch
  777. wrapper.registry = types.MappingProxyType(registry)
  778. wrapper._clear_cache = dispatch_cache.clear
  779. update_wrapper(wrapper, func)
  780. return wrapper
  781. # Descriptor version
  782. class singledispatchmethod:
  783. """Single-dispatch generic method descriptor.
  784. Supports wrapping existing descriptors and handles non-descriptor
  785. callables as instance methods.
  786. """
  787. def __init__(self, func):
  788. if not callable(func) and not hasattr(func, "__get__"):
  789. raise TypeError(f"{func!r} is not callable or a descriptor")
  790. self.dispatcher = singledispatch(func)
  791. self.func = func
  792. def register(self, cls, method=None):
  793. """generic_method.register(cls, func) -> func
  794. Registers a new implementation for the given *cls* on a *generic_method*.
  795. """
  796. return self.dispatcher.register(cls, func=method)
  797. def __get__(self, obj, cls=None):
  798. def _method(*args, **kwargs):
  799. method = self.dispatcher.dispatch(args[0].__class__)
  800. return method.__get__(obj, cls)(*args, **kwargs)
  801. _method.__isabstractmethod__ = self.__isabstractmethod__
  802. _method.register = self.register
  803. update_wrapper(_method, self.func)
  804. return _method
  805. @property
  806. def __isabstractmethod__(self):
  807. return getattr(self.func, '__isabstractmethod__', False)
  808. ################################################################################
  809. ### cached_property() - property result cached as instance attribute
  810. ################################################################################
  811. _NOT_FOUND = object()
  812. class cached_property:
  813. def __init__(self, func):
  814. self.func = func
  815. self.attrname = None
  816. self.__doc__ = func.__doc__
  817. def __set_name__(self, owner, name):
  818. if self.attrname is None:
  819. self.attrname = name
  820. elif name != self.attrname:
  821. raise TypeError(
  822. "Cannot assign the same cached_property to two different names "
  823. f"({self.attrname!r} and {name!r})."
  824. )
  825. def __get__(self, instance, owner=None):
  826. if instance is None:
  827. return self
  828. if self.attrname is None:
  829. raise TypeError(
  830. "Cannot use cached_property instance without calling __set_name__ on it.")
  831. try:
  832. cache = instance.__dict__
  833. except AttributeError: # not all objects have __dict__ (e.g. class defines slots)
  834. msg = (
  835. f"No '__dict__' attribute on {type(instance).__name__!r} "
  836. f"instance to cache {self.attrname!r} property."
  837. )
  838. raise TypeError(msg) from None
  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)