functional.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.utils.functional
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. Utilities for functions.
  6. """
  7. from __future__ import absolute_import
  8. from __future__ import with_statement
  9. import threading
  10. from functools import wraps
  11. from itertools import islice
  12. from kombu.utils import cached_property
  13. from kombu.utils.functional import promise, maybe_promise
  14. from kombu.utils.compat import OrderedDict, next
  15. from .compat import UserDict, UserList
  16. KEYWORD_MARK = object()
  17. class LRUCache(UserDict):
  18. """LRU Cache implementation using a doubly linked list to track access.
  19. :keyword limit: The maximum number of keys to keep in the cache.
  20. When a new key is inserted and the limit has been exceeded,
  21. the *Least Recently Used* key will be discarded from the
  22. cache.
  23. """
  24. def __init__(self, limit=None):
  25. self.limit = limit
  26. self.mutex = threading.RLock()
  27. self.data = OrderedDict()
  28. def __getitem__(self, key):
  29. with self.mutex:
  30. value = self[key] = self.data.pop(key)
  31. return value
  32. def keys(self):
  33. # userdict.keys in py3k calls __getitem__
  34. return self.data.keys()
  35. def values(self):
  36. return list(self._iterate_values())
  37. def items(self):
  38. return list(self._iterate_items())
  39. def update(self, *args, **kwargs):
  40. with self.mutex:
  41. data, limit = self.data, self.limit
  42. data.update(*args, **kwargs)
  43. if limit and len(data) > limit:
  44. # pop additional items in case limit exceeded
  45. # negative overflow will lead to an empty list
  46. for item in islice(iter(data), len(data) - limit):
  47. data.pop(item)
  48. def __setitem__(self, key, value):
  49. # remove least recently used key.
  50. with self.mutex:
  51. if self.limit and len(self.data) >= self.limit:
  52. self.data.pop(iter(self.data).next())
  53. self.data[key] = value
  54. def __iter__(self):
  55. return iter(self.data)
  56. def _iterate_items(self):
  57. for k in self:
  58. try:
  59. yield (k, self.data[k])
  60. except KeyError: # pragma: no cover
  61. pass
  62. iteritems = _iterate_items
  63. def _iterate_values(self):
  64. for k in self:
  65. try:
  66. yield self.data[k]
  67. except KeyError: # pragma: no cover
  68. pass
  69. itervalues = _iterate_values
  70. def incr(self, key, delta=1):
  71. with self.mutex:
  72. # this acts as memcached does- store as a string, but return a
  73. # integer as long as it exists and we can cast it
  74. newval = int(self.data.pop(key)) + delta
  75. self[key] = str(newval)
  76. return newval
  77. def __getstate__(self):
  78. d = dict(vars(self))
  79. d.pop('mutex')
  80. return d
  81. def __setstate__(self, state):
  82. self.__dict__ = state
  83. self.mutex = threading.RLock()
  84. def is_list(l):
  85. """Returns true if object is list-like, but not a dict or string."""
  86. return hasattr(l, '__iter__') and not isinstance(l, (dict, basestring))
  87. def maybe_list(l):
  88. """Returns list of one element if ``l`` is a scalar."""
  89. return l if l is None or is_list(l) else [l]
  90. def memoize(maxsize=None, Cache=LRUCache):
  91. def _memoize(fun):
  92. mutex = threading.Lock()
  93. cache = Cache(limit=maxsize)
  94. @wraps(fun)
  95. def _M(*args, **kwargs):
  96. key = args + (KEYWORD_MARK, ) + tuple(sorted(kwargs.iteritems()))
  97. try:
  98. with mutex:
  99. value = cache[key]
  100. except KeyError:
  101. value = fun(*args, **kwargs)
  102. _M.misses += 1
  103. with mutex:
  104. cache[key] = value
  105. else:
  106. _M.hits += 1
  107. return value
  108. def clear():
  109. """Clear the cache and reset cache statistics."""
  110. cache.clear()
  111. _M.hits = _M.misses = 0
  112. _M.hits = _M.misses = 0
  113. _M.clear = clear
  114. _M.original_func = fun
  115. return _M
  116. return _memoize
  117. class mpromise(promise):
  118. """Memoized promise.
  119. The function is only evaluated once, every subsequent access
  120. will return the same value.
  121. .. attribute:: evaluated
  122. Set to to :const:`True` after the promise has been evaluated.
  123. """
  124. evaluated = False
  125. _value = None
  126. def evaluate(self):
  127. if not self.evaluated:
  128. self._value = super(mpromise, self).evaluate()
  129. self.evaluated = True
  130. return self._value
  131. def noop(*args, **kwargs):
  132. """No operation.
  133. Takes any arguments/keyword arguments and does nothing.
  134. """
  135. pass
  136. def first(predicate, it):
  137. """Returns the first element in `iterable` that `predicate` returns a
  138. :const:`True` value for.
  139. If `predicate` is None it will return the first item that is not None.
  140. """
  141. return next(
  142. (v for v in it if (predicate(v) if predicate else v is not None)),
  143. None,
  144. )
  145. def firstmethod(method):
  146. """Returns a function that with a list of instances,
  147. finds the first instance that returns a value for the given method.
  148. The list can also contain promises (:class:`promise`.)
  149. """
  150. def _matcher(it, *args, **kwargs):
  151. for obj in it:
  152. try:
  153. answer = getattr(maybe_promise(obj), method)(*args, **kwargs)
  154. except AttributeError:
  155. pass
  156. else:
  157. if answer is not None:
  158. return answer
  159. return _matcher
  160. def chunks(it, n):
  161. """Split an iterator into chunks with `n` elements each.
  162. Examples
  163. # n == 2
  164. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2)
  165. >>> list(x)
  166. [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
  167. # n == 3
  168. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3)
  169. >>> list(x)
  170. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
  171. """
  172. # XXX This function is not used anymore, at least not by Celery itself.
  173. for first in it:
  174. yield [first] + list(islice(it, n - 1))
  175. def padlist(container, size, default=None):
  176. """Pad list with default elements.
  177. Examples:
  178. >>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3)
  179. ('George', 'Costanza', 'NYC')
  180. >>> first, last, city = padlist(['George', 'Costanza'], 3)
  181. ('George', 'Costanza', None)
  182. >>> first, last, city, planet = padlist(['George', 'Costanza',
  183. 'NYC'], 4, default='Earth')
  184. ('George', 'Costanza', 'NYC', 'Earth')
  185. """
  186. return list(container)[:size] + [default] * (size - len(container))
  187. def mattrgetter(*attrs):
  188. """Like :func:`operator.itemgetter` but returns :const:`None` on missing
  189. attributes instead of raising :exc:`AttributeError`."""
  190. return lambda obj: dict((attr, getattr(obj, attr, None))
  191. for attr in attrs)
  192. def uniq(it):
  193. """Returns all unique elements in ``it``, preserving order."""
  194. seen = set()
  195. return (seen.add(obj) or obj for obj in it if obj not in seen)
  196. def regen(it):
  197. """Regen takes any iterable, and if the object is an
  198. generator it will cache the evaluated list on first access,
  199. so that the generator can be "consumed" multiple times."""
  200. if isinstance(it, (list, tuple)):
  201. return it
  202. return _regen(it)
  203. class _regen(UserList, list):
  204. # must be subclass of list so that json can encode.
  205. def __init__(self, it):
  206. self.__it = it
  207. @cached_property
  208. def data(self):
  209. return list(self.__it)
  210. def __iter__(self): # needed for Python 2.5
  211. return iter(self.data)