functools.py 37 KB

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