cacheutils.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Mahmoud Hashemi
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. # * The names of the contributors may not be used to endorse or
  17. # promote products derived from this software without specific
  18. # prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """``cacheutils`` contains consistent implementations of fundamental
  32. cache types. Currently there are two to choose from:
  33. * :class:`LRI` - Least-recently inserted
  34. * :class:`LRU` - Least-recently used
  35. Both caches are :class:`dict` subtypes, designed to be as
  36. interchangeable as possible, to facilitate experimentation. A key
  37. practice with performance enhancement with caching is ensuring that
  38. the caching strategy is working. If the cache is constantly missing,
  39. it is just adding more overhead and code complexity. The standard
  40. statistics are:
  41. * ``hit_count`` - the number of times the queried key has been in
  42. the cache
  43. * ``miss_count`` - the number of times a key has been absent and/or
  44. fetched by the cache
  45. * ``soft_miss_count`` - the number of times a key has been absent,
  46. but a default has been provided by the caller, as with
  47. :meth:`dict.get` and :meth:`dict.setdefault`. Soft misses are a
  48. subset of misses, so this number is always less than or equal to
  49. ``miss_count``.
  50. Additionally, ``cacheutils`` provides :class:`ThresholdCounter`, a
  51. cache-like bounded counter useful for online statistics collection.
  52. Learn more about `caching algorithms on Wikipedia
  53. <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_.
  54. """
  55. # TODO: TimedLRI
  56. # TODO: support 0 max_size?
  57. import heapq
  58. import weakref
  59. import itertools
  60. from operator import attrgetter
  61. try:
  62. from threading import RLock
  63. except Exception:
  64. class RLock(object):
  65. 'Dummy reentrant lock for builds without threads'
  66. def __enter__(self):
  67. pass
  68. def __exit__(self, exctype, excinst, exctb):
  69. pass
  70. try:
  71. from .typeutils import make_sentinel
  72. _MISSING = make_sentinel(var_name='_MISSING')
  73. _KWARG_MARK = make_sentinel(var_name='_KWARG_MARK')
  74. except ImportError:
  75. _MISSING = object()
  76. _KWARG_MARK = object()
  77. try:
  78. xrange
  79. except NameError:
  80. # py3
  81. xrange = range
  82. unicode, str, bytes, basestring = str, bytes, bytes, (str, bytes)
  83. PREV, NEXT, KEY, VALUE = range(4) # names for the link fields
  84. DEFAULT_MAX_SIZE = 128
  85. class LRI(dict):
  86. """The ``LRI`` implements the basic *Least Recently Inserted* strategy to
  87. caching. One could also think of this as a ``SizeLimitedDefaultDict``.
  88. *on_miss* is a callable that accepts the missing key (as opposed
  89. to :class:`collections.defaultdict`'s "default_factory", which
  90. accepts no arguments.) Also note that, like the :class:`LRI`,
  91. the ``LRI`` is instrumented with statistics tracking.
  92. >>> cap_cache = LRI(max_size=2)
  93. >>> cap_cache['a'], cap_cache['b'] = 'A', 'B'
  94. >>> from pprint import pprint as pp
  95. >>> pp(dict(cap_cache))
  96. {'a': 'A', 'b': 'B'}
  97. >>> [cap_cache['b'] for i in range(3)][0]
  98. 'B'
  99. >>> cap_cache['c'] = 'C'
  100. >>> print(cap_cache.get('a'))
  101. None
  102. >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count
  103. (3, 1, 1)
  104. """
  105. def __init__(self, max_size=DEFAULT_MAX_SIZE, values=None,
  106. on_miss=None):
  107. if max_size <= 0:
  108. raise ValueError('expected max_size > 0, not %r' % max_size)
  109. self.hit_count = self.miss_count = self.soft_miss_count = 0
  110. self.max_size = max_size
  111. self._lock = RLock()
  112. self._init_ll()
  113. if on_miss is not None and not callable(on_miss):
  114. raise TypeError('expected on_miss to be a callable'
  115. ' (or None), not %r' % on_miss)
  116. self.on_miss = on_miss
  117. if values:
  118. self.update(values)
  119. # TODO: fromkeys()?
  120. # linked list manipulation methods.
  121. #
  122. # invariants:
  123. # 1) 'anchor' is the sentinel node in the doubly linked list. there is
  124. # always only one, and its KEY and VALUE are both _MISSING.
  125. # 2) the most recently accessed node comes immediately before 'anchor'.
  126. # 3) the least recently accessed node comes immediately after 'anchor'.
  127. def _init_ll(self):
  128. anchor = []
  129. anchor[:] = [anchor, anchor, _MISSING, _MISSING]
  130. # a link lookup table for finding linked list links in O(1)
  131. # time.
  132. self._link_lookup = {}
  133. self._anchor = anchor
  134. def _print_ll(self):
  135. print('***')
  136. for (key, val) in self._get_flattened_ll():
  137. print(key, val)
  138. print('***')
  139. return
  140. def _get_flattened_ll(self):
  141. flattened_list = []
  142. link = self._anchor
  143. while True:
  144. flattened_list.append((link[KEY], link[VALUE]))
  145. link = link[NEXT]
  146. if link is self._anchor:
  147. break
  148. return flattened_list
  149. def _get_link_and_move_to_front_of_ll(self, key):
  150. # find what will become the newest link. this may raise a
  151. # KeyError, which is useful to __getitem__ and __setitem__
  152. newest = self._link_lookup[key]
  153. # splice out what will become the newest link.
  154. newest[PREV][NEXT] = newest[NEXT]
  155. newest[NEXT][PREV] = newest[PREV]
  156. # move what will become the newest link immediately before
  157. # anchor (invariant 2)
  158. anchor = self._anchor
  159. second_newest = anchor[PREV]
  160. second_newest[NEXT] = anchor[PREV] = newest
  161. newest[PREV] = second_newest
  162. newest[NEXT] = anchor
  163. return newest
  164. def _set_key_and_add_to_front_of_ll(self, key, value):
  165. # create a new link and place it immediately before anchor
  166. # (invariant 2).
  167. anchor = self._anchor
  168. second_newest = anchor[PREV]
  169. newest = [second_newest, anchor, key, value]
  170. second_newest[NEXT] = anchor[PREV] = newest
  171. self._link_lookup[key] = newest
  172. def _set_key_and_evict_last_in_ll(self, key, value):
  173. # the link after anchor is the oldest in the linked list
  174. # (invariant 3). the current anchor becomes a link that holds
  175. # the newest key, and the oldest link becomes the new anchor
  176. # (invariant 1). now the newest link comes before anchor
  177. # (invariant 2). no links are moved; only their keys
  178. # and values are changed.
  179. oldanchor = self._anchor
  180. oldanchor[KEY] = key
  181. oldanchor[VALUE] = value
  182. self._anchor = anchor = oldanchor[NEXT]
  183. evicted = anchor[KEY]
  184. anchor[KEY] = anchor[VALUE] = _MISSING
  185. del self._link_lookup[evicted]
  186. self._link_lookup[key] = oldanchor
  187. return evicted
  188. def _remove_from_ll(self, key):
  189. # splice a link out of the list and drop it from our lookup
  190. # table.
  191. link = self._link_lookup.pop(key)
  192. link[PREV][NEXT] = link[NEXT]
  193. link[NEXT][PREV] = link[PREV]
  194. def __setitem__(self, key, value):
  195. with self._lock:
  196. try:
  197. link = self._get_link_and_move_to_front_of_ll(key)
  198. except KeyError:
  199. if len(self) < self.max_size:
  200. self._set_key_and_add_to_front_of_ll(key, value)
  201. else:
  202. evicted = self._set_key_and_evict_last_in_ll(key, value)
  203. super(LRI, self).__delitem__(evicted)
  204. super(LRI, self).__setitem__(key, value)
  205. else:
  206. link[VALUE] = value
  207. def __getitem__(self, key):
  208. with self._lock:
  209. try:
  210. link = self._link_lookup[key]
  211. except KeyError:
  212. self.miss_count += 1
  213. if not self.on_miss:
  214. raise
  215. ret = self[key] = self.on_miss(key)
  216. return ret
  217. self.hit_count += 1
  218. return link[VALUE]
  219. def get(self, key, default=None):
  220. try:
  221. return self[key]
  222. except KeyError:
  223. self.soft_miss_count += 1
  224. return default
  225. def __delitem__(self, key):
  226. with self._lock:
  227. super(LRI, self).__delitem__(key)
  228. self._remove_from_ll(key)
  229. def pop(self, key, default=_MISSING):
  230. # NB: hit/miss counts are bypassed for pop()
  231. with self._lock:
  232. try:
  233. ret = super(LRI, self).pop(key)
  234. except KeyError:
  235. if default is _MISSING:
  236. raise
  237. ret = default
  238. else:
  239. self._remove_from_ll(key)
  240. return ret
  241. def popitem(self):
  242. with self._lock:
  243. item = super(LRI, self).popitem()
  244. self._remove_from_ll(item[0])
  245. return item
  246. def clear(self):
  247. with self._lock:
  248. super(LRI, self).clear()
  249. self._init_ll()
  250. def copy(self):
  251. return self.__class__(max_size=self.max_size, values=self)
  252. def setdefault(self, key, default=None):
  253. with self._lock:
  254. try:
  255. return self[key]
  256. except KeyError:
  257. self.soft_miss_count += 1
  258. self[key] = default
  259. return default
  260. def update(self, E, **F):
  261. # E and F are throwback names to the dict() __doc__
  262. with self._lock:
  263. if E is self:
  264. return
  265. setitem = self.__setitem__
  266. if callable(getattr(E, 'keys', None)):
  267. for k in E.keys():
  268. setitem(k, E[k])
  269. else:
  270. for k, v in E:
  271. setitem(k, v)
  272. for k in F:
  273. setitem(k, F[k])
  274. return
  275. def __eq__(self, other):
  276. with self._lock:
  277. if self is other:
  278. return True
  279. if len(other) != len(self):
  280. return False
  281. if not isinstance(other, LRI):
  282. return other == self
  283. return super(LRI, self).__eq__(other)
  284. def __ne__(self, other):
  285. return not (self == other)
  286. def __repr__(self):
  287. cn = self.__class__.__name__
  288. val_map = super(LRI, self).__repr__()
  289. return ('%s(max_size=%r, on_miss=%r, values=%s)'
  290. % (cn, self.max_size, self.on_miss, val_map))
  291. class LRU(LRI):
  292. """The ``LRU`` is :class:`dict` subtype implementation of the
  293. *Least-Recently Used* caching strategy.
  294. Args:
  295. max_size (int): Max number of items to cache. Defaults to ``128``.
  296. values (iterable): Initial values for the cache. Defaults to ``None``.
  297. on_miss (callable): a callable which accepts a single argument, the
  298. key not present in the cache, and returns the value to be cached.
  299. >>> cap_cache = LRU(max_size=2)
  300. >>> cap_cache['a'], cap_cache['b'] = 'A', 'B'
  301. >>> from pprint import pprint as pp
  302. >>> pp(dict(cap_cache))
  303. {'a': 'A', 'b': 'B'}
  304. >>> [cap_cache['b'] for i in range(3)][0]
  305. 'B'
  306. >>> cap_cache['c'] = 'C'
  307. >>> print(cap_cache.get('a'))
  308. None
  309. This cache is also instrumented with statistics
  310. collection. ``hit_count``, ``miss_count``, and ``soft_miss_count``
  311. are all integer members that can be used to introspect the
  312. performance of the cache. ("Soft" misses are misses that did not
  313. raise :exc:`KeyError`, e.g., ``LRU.get()`` or ``on_miss`` was used to
  314. cache a default.
  315. >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count
  316. (3, 1, 1)
  317. Other than the size-limiting caching behavior and statistics,
  318. ``LRU`` acts like its parent class, the built-in Python :class:`dict`.
  319. """
  320. def __getitem__(self, key):
  321. with self._lock:
  322. try:
  323. link = self._get_link_and_move_to_front_of_ll(key)
  324. except KeyError:
  325. self.miss_count += 1
  326. if not self.on_miss:
  327. raise
  328. ret = self[key] = self.on_miss(key)
  329. return ret
  330. self.hit_count += 1
  331. return link[VALUE]
  332. ### Cached decorator
  333. # Key-making technique adapted from Python 3.4's functools
  334. class _HashedKey(list):
  335. """The _HashedKey guarantees that hash() will be called no more than once
  336. per cached function invocation.
  337. """
  338. __slots__ = 'hash_value'
  339. def __init__(self, key):
  340. self[:] = key
  341. self.hash_value = hash(tuple(key))
  342. def __hash__(self):
  343. return self.hash_value
  344. def __repr__(self):
  345. return '%s(%s)' % (self.__class__.__name__, list.__repr__(self))
  346. def make_cache_key(args, kwargs, typed=False,
  347. kwarg_mark=_KWARG_MARK,
  348. fasttypes=frozenset([int, str, frozenset, type(None)])):
  349. """Make a generic key from a function's positional and keyword
  350. arguments, suitable for use in caches. Arguments within *args* and
  351. *kwargs* must be `hashable`_. If *typed* is ``True``, ``3`` and
  352. ``3.0`` will be treated as separate keys.
  353. The key is constructed in a way that is flat as possible rather than
  354. as a nested structure that would take more memory.
  355. If there is only a single argument and its data type is known to cache
  356. its hash value, then that argument is returned without a wrapper. This
  357. saves space and improves lookup speed.
  358. >>> tuple(make_cache_key(('a', 'b'), {'c': ('d')}))
  359. ('a', 'b', _KWARG_MARK, ('c', 'd'))
  360. .. _hashable: https://docs.python.org/2/glossary.html#term-hashable
  361. """
  362. # key = [func_name] if func_name else []
  363. # key.extend(args)
  364. key = list(args)
  365. if kwargs:
  366. sorted_items = sorted(kwargs.items())
  367. key.append(kwarg_mark)
  368. key.extend(sorted_items)
  369. if typed:
  370. key.extend([type(v) for v in args])
  371. if kwargs:
  372. key.extend([type(v) for k, v in sorted_items])
  373. elif len(key) == 1 and type(key[0]) in fasttypes:
  374. return key[0]
  375. return _HashedKey(key)
  376. # for backwards compatibility in case someone was importing it
  377. _make_cache_key = make_cache_key
  378. class CachedFunction(object):
  379. """This type is used by :func:`cached`, below. Instances of this
  380. class are used to wrap functions in caching logic.
  381. """
  382. def __init__(self, func, cache, scoped=True, typed=False, key=None):
  383. self.func = func
  384. if callable(cache):
  385. self.get_cache = cache
  386. elif not (callable(getattr(cache, '__getitem__', None))
  387. and callable(getattr(cache, '__setitem__', None))):
  388. raise TypeError('expected cache to be a dict-like object,'
  389. ' or callable returning a dict-like object, not %r'
  390. % cache)
  391. else:
  392. def _get_cache():
  393. return cache
  394. self.get_cache = _get_cache
  395. self.scoped = scoped
  396. self.typed = typed
  397. self.key_func = key or make_cache_key
  398. def __call__(self, *args, **kwargs):
  399. cache = self.get_cache()
  400. key = self.key_func(args, kwargs, typed=self.typed)
  401. try:
  402. ret = cache[key]
  403. except KeyError:
  404. ret = cache[key] = self.func(*args, **kwargs)
  405. return ret
  406. def __repr__(self):
  407. cn = self.__class__.__name__
  408. if self.typed or not self.scoped:
  409. return ("%s(func=%r, scoped=%r, typed=%r)"
  410. % (cn, self.func, self.scoped, self.typed))
  411. return "%s(func=%r)" % (cn, self.func)
  412. class CachedMethod(object):
  413. """Similar to :class:`CachedFunction`, this type is used by
  414. :func:`cachedmethod` to wrap methods in caching logic.
  415. """
  416. def __init__(self, func, cache, scoped=True, typed=False, key=None):
  417. self.func = func
  418. self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False)
  419. if isinstance(cache, basestring):
  420. self.get_cache = attrgetter(cache)
  421. elif callable(cache):
  422. self.get_cache = cache
  423. elif not (callable(getattr(cache, '__getitem__', None))
  424. and callable(getattr(cache, '__setitem__', None))):
  425. raise TypeError('expected cache to be an attribute name,'
  426. ' dict-like object, or callable returning'
  427. ' a dict-like object, not %r' % cache)
  428. else:
  429. def _get_cache(obj):
  430. return cache
  431. self.get_cache = _get_cache
  432. self.scoped = scoped
  433. self.typed = typed
  434. self.key_func = key or make_cache_key
  435. self.bound_to = None
  436. def __get__(self, obj, objtype=None):
  437. if obj is None:
  438. return self
  439. cls = self.__class__
  440. ret = cls(self.func, self.get_cache, typed=self.typed,
  441. scoped=self.scoped, key=self.key_func)
  442. ret.bound_to = obj
  443. return ret
  444. def __call__(self, *args, **kwargs):
  445. obj = args[0] if self.bound_to is None else self.bound_to
  446. cache = self.get_cache(obj)
  447. key_args = (self.bound_to, self.func) + args if self.scoped else args
  448. key = self.key_func(key_args, kwargs, typed=self.typed)
  449. try:
  450. ret = cache[key]
  451. except KeyError:
  452. if self.bound_to is not None:
  453. args = (self.bound_to,) + args
  454. ret = cache[key] = self.func(*args, **kwargs)
  455. return ret
  456. def __repr__(self):
  457. cn = self.__class__.__name__
  458. args = (cn, self.func, self.scoped, self.typed)
  459. if self.bound_to is not None:
  460. args += (self.bound_to,)
  461. return ('<%s func=%r scoped=%r typed=%r bound_to=%r>' % args)
  462. return ("%s(func=%r, scoped=%r, typed=%r)" % args)
  463. def cached(cache, scoped=True, typed=False, key=None):
  464. """Cache any function with the cache object of your choosing. Note
  465. that the function wrapped should take only `hashable`_ arguments.
  466. Args:
  467. cache (Mapping): Any :class:`dict`-like object suitable for
  468. use as a cache. Instances of the :class:`LRU` and
  469. :class:`LRI` are good choices, but a plain :class:`dict`
  470. can work in some cases, as well. This argument can also be
  471. a callable which accepts no arguments and returns a mapping.
  472. scoped (bool): Whether the function itself is part of the
  473. cache key. ``True`` by default, different functions will
  474. not read one another's cache entries, but can evict one
  475. another's results. ``False`` can be useful for certain
  476. shared cache use cases. More advanced behavior can be
  477. produced through the *key* argument.
  478. typed (bool): Whether to factor argument types into the cache
  479. check. Default ``False``, setting to ``True`` causes the
  480. cache keys for ``3`` and ``3.0`` to be considered unequal.
  481. >>> my_cache = LRU()
  482. >>> @cached(my_cache)
  483. ... def cached_lower(x):
  484. ... return x.lower()
  485. ...
  486. >>> cached_lower("CaChInG's FuN AgAiN!")
  487. "caching's fun again!"
  488. >>> len(my_cache)
  489. 1
  490. .. _hashable: https://docs.python.org/2/glossary.html#term-hashable
  491. """
  492. def cached_func_decorator(func):
  493. return CachedFunction(func, cache, scoped=scoped, typed=typed, key=key)
  494. return cached_func_decorator
  495. def cachedmethod(cache, scoped=True, typed=False, key=None):
  496. """Similar to :func:`cached`, ``cachedmethod`` is used to cache
  497. methods based on their arguments, using any :class:`dict`-like
  498. *cache* object.
  499. Args:
  500. cache (str/Mapping/callable): Can be the name of an attribute
  501. on the instance, any Mapping/:class:`dict`-like object, or
  502. a callable which returns a Mapping.
  503. scoped (bool): Whether the method itself and the object it is
  504. bound to are part of the cache keys. ``True`` by default,
  505. different methods will not read one another's cache
  506. results. ``False`` can be useful for certain shared cache
  507. use cases. More advanced behavior can be produced through
  508. the *key* arguments.
  509. typed (bool): Whether to factor argument types into the cache
  510. check. Default ``False``, setting to ``True`` causes the
  511. cache keys for ``3`` and ``3.0`` to be considered unequal.
  512. key (callable): A callable with a signature that matches
  513. :func:`make_cache_key` that returns a tuple of hashable
  514. values to be used as the key in the cache.
  515. >>> class Lowerer(object):
  516. ... def __init__(self):
  517. ... self.cache = LRI()
  518. ...
  519. ... @cachedmethod('cache')
  520. ... def lower(self, text):
  521. ... return text.lower()
  522. ...
  523. >>> lowerer = Lowerer()
  524. >>> lowerer.lower('WOW WHO COULD GUESS CACHING COULD BE SO NEAT')
  525. 'wow who could guess caching could be so neat'
  526. >>> len(lowerer.cache)
  527. 1
  528. """
  529. def cached_method_decorator(func):
  530. return CachedMethod(func, cache, scoped=scoped, typed=typed, key=key)
  531. return cached_method_decorator
  532. class cachedproperty(object):
  533. """The ``cachedproperty`` is used similar to :class:`property`, except
  534. that the wrapped method is only called once. This is commonly used
  535. to implement lazy attributes.
  536. After the property has been accessed, the value is stored on the
  537. instance itself, using the same name as the cachedproperty. This
  538. allows the cache to be cleared with :func:`delattr`, or through
  539. manipulating the object's ``__dict__``.
  540. """
  541. def __init__(self, func):
  542. self.__doc__ = getattr(func, '__doc__')
  543. self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False)
  544. self.func = func
  545. def __get__(self, obj, objtype=None):
  546. if obj is None:
  547. return self
  548. value = obj.__dict__[self.func.__name__] = self.func(obj)
  549. return value
  550. def __repr__(self):
  551. cn = self.__class__.__name__
  552. return '<%s func=%s>' % (cn, self.func)
  553. class ThresholdCounter(object):
  554. """A **bounded** dict-like Mapping from keys to counts. The
  555. ThresholdCounter automatically compacts after every (1 /
  556. *threshold*) additions, maintaining exact counts for any keys
  557. whose count represents at least a *threshold* ratio of the total
  558. data. In other words, if a particular key is not present in the
  559. ThresholdCounter, its count represents less than *threshold* of
  560. the total data.
  561. >>> tc = ThresholdCounter(threshold=0.1)
  562. >>> tc.add(1)
  563. >>> tc.items()
  564. [(1, 1)]
  565. >>> tc.update([2] * 10)
  566. >>> tc.get(1)
  567. 0
  568. >>> tc.add(5)
  569. >>> 5 in tc
  570. True
  571. >>> len(list(tc.elements()))
  572. 11
  573. As you can see above, the API is kept similar to
  574. :class:`collections.Counter`. The most notable feature omissions
  575. being that counted items cannot be set directly, uncounted, or
  576. removed, as this would disrupt the math.
  577. Use the ThresholdCounter when you need best-effort long-lived
  578. counts for dynamically-keyed data. Without a bounded datastructure
  579. such as this one, the dynamic keys often represent a memory leak
  580. and can impact application reliability. The ThresholdCounter's
  581. item replacement strategy is fully deterministic and can be
  582. thought of as *Amortized Least Relevant*. The absolute upper bound
  583. of keys it will store is *(2/threshold)*, but realistically
  584. *(1/threshold)* is expected for uniformly random datastreams, and
  585. one or two orders of magnitude better for real-world data.
  586. This algorithm is an implementation of the Lossy Counting
  587. algorithm described in "Approximate Frequency Counts over Data
  588. Streams" by Manku & Motwani. Hat tip to Kurt Rose for discovery
  589. and initial implementation.
  590. """
  591. # TODO: hit_count/miss_count?
  592. def __init__(self, threshold=0.001):
  593. if not 0 < threshold < 1:
  594. raise ValueError('expected threshold between 0 and 1, not: %r'
  595. % threshold)
  596. self.total = 0
  597. self._count_map = {}
  598. self._threshold = threshold
  599. self._thresh_count = int(1 / threshold)
  600. self._cur_bucket = 1
  601. @property
  602. def threshold(self):
  603. return self._threshold
  604. def add(self, key):
  605. """Increment the count of *key* by 1, automatically adding it if it
  606. does not exist.
  607. Cache compaction is triggered every *1/threshold* additions.
  608. """
  609. self.total += 1
  610. try:
  611. self._count_map[key][0] += 1
  612. except KeyError:
  613. self._count_map[key] = [1, self._cur_bucket - 1]
  614. if self.total % self._thresh_count == 0:
  615. self._count_map = dict([(k, v) for k, v in self._count_map.items()
  616. if sum(v) > self._cur_bucket])
  617. self._cur_bucket += 1
  618. return
  619. def elements(self):
  620. """Return an iterator of all the common elements tracked by the
  621. counter. Yields each key as many times as it has been seen.
  622. """
  623. repeaters = itertools.starmap(itertools.repeat, self.iteritems())
  624. return itertools.chain.from_iterable(repeaters)
  625. def most_common(self, n=None):
  626. """Get the top *n* keys and counts as tuples. If *n* is omitted,
  627. returns all the pairs.
  628. """
  629. if n <= 0:
  630. return []
  631. ret = sorted(self.iteritems(), key=lambda x: x[1], reverse=True)
  632. if n is None or n >= len(ret):
  633. return ret
  634. return ret[:n]
  635. def get_common_count(self):
  636. """Get the sum of counts for keys exceeding the configured data
  637. threshold.
  638. """
  639. return sum([count for count, _ in self._count_map.values()])
  640. def get_uncommon_count(self):
  641. """Get the sum of counts for keys that were culled because the
  642. associated counts represented less than the configured
  643. threshold. The long-tail counts.
  644. """
  645. return self.total - self.get_common_count()
  646. def get_commonality(self):
  647. """Get a float representation of the effective count accuracy. The
  648. higher the number, the less uniform the keys being added, and
  649. the higher accuracy and efficiency of the ThresholdCounter.
  650. If a stronger measure of data cardinality is required,
  651. consider using hyperloglog.
  652. """
  653. return float(self.get_common_count()) / self.total
  654. def __getitem__(self, key):
  655. return self._count_map[key][0]
  656. def __len__(self):
  657. return len(self._count_map)
  658. def __contains__(self, key):
  659. return key in self._count_map
  660. def iterkeys(self):
  661. return iter(self._count_map)
  662. def keys(self):
  663. return list(self.iterkeys())
  664. def itervalues(self):
  665. count_map = self._count_map
  666. for k in count_map:
  667. yield count_map[k][0]
  668. def values(self):
  669. return list(self.itervalues())
  670. def iteritems(self):
  671. count_map = self._count_map
  672. for k in count_map:
  673. yield (k, count_map[k][0])
  674. def items(self):
  675. return list(self.iteritems())
  676. def get(self, key, default=0):
  677. "Get count for *key*, defaulting to 0."
  678. try:
  679. return self[key]
  680. except KeyError:
  681. return default
  682. def update(self, iterable, **kwargs):
  683. """Like dict.update() but add counts instead of replacing them, used
  684. to add multiple items in one call.
  685. Source can be an iterable of keys to add, or a mapping of keys
  686. to integer counts.
  687. """
  688. if iterable is not None:
  689. if callable(getattr(iterable, 'iteritems', None)):
  690. for key, count in iterable.iteritems():
  691. for i in xrange(count):
  692. self.add(key)
  693. else:
  694. for key in iterable:
  695. self.add(key)
  696. if kwargs:
  697. self.update(kwargs)
  698. class MinIDMap(object):
  699. """
  700. Assigns arbitrary weakref-able objects the smallest possible unique
  701. integer IDs, such that no two objects have the same ID at the same
  702. time.
  703. Maps arbitrary hashable objects to IDs.
  704. Based on https://gist.github.com/kurtbrose/25b48114de216a5e55df
  705. """
  706. def __init__(self):
  707. self.mapping = weakref.WeakKeyDictionary()
  708. self.ref_map = {}
  709. self.free = []
  710. def get(self, a):
  711. try:
  712. return self.mapping[a][0] # if object is mapped, return ID
  713. except KeyError:
  714. pass
  715. if self.free: # if there are any free IDs, use the smallest
  716. nxt = heapq.heappop(self.free)
  717. else: # if there are no free numbers, use the next highest ID
  718. nxt = len(self.mapping)
  719. ref = weakref.ref(a, self._clean)
  720. self.mapping[a] = (nxt, ref)
  721. self.ref_map[ref] = nxt
  722. return nxt
  723. def drop(self, a):
  724. freed, ref = self.mapping[a]
  725. del self.mapping[a]
  726. del self.ref_map[ref]
  727. heapq.heappush(self.free, freed)
  728. def _clean(self, ref):
  729. print(self.ref_map[ref])
  730. heapq.heappush(self.free, self.ref_map[ref])
  731. del self.ref_map[ref]
  732. def __contains__(self, a):
  733. return a in self.mapping
  734. def __iter__(self):
  735. return iter(self.mapping)
  736. def __len__(self):
  737. return self.mapping.__len__()
  738. def iteritems(self):
  739. return iter((k, self.mapping[k][0]) for k in iter(self.mapping))
  740. # end cacheutils.py