functools.py 36 KB

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