functools.py 37 KB

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