functools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. from __future__ import (
  2. absolute_import, unicode_literals, print_function, division,
  3. )
  4. import functools
  5. import time
  6. import warnings
  7. import inspect
  8. import collections
  9. from itertools import count
  10. __metaclass__ = type
  11. try:
  12. from functools import lru_cache
  13. except ImportError:
  14. try:
  15. from backports.functools_lru_cache import lru_cache
  16. except ImportError:
  17. try:
  18. from functools32 import lru_cache
  19. except ImportError:
  20. warnings.warn("No lru_cache available")
  21. import more_itertools.recipes
  22. def compose(*funcs):
  23. """
  24. Compose any number of unary functions into a single unary function.
  25. >>> import textwrap
  26. >>> from six import text_type
  27. >>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))
  28. >>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped
  29. True
  30. Compose also allows the innermost function to take arbitrary arguments.
  31. >>> round_three = lambda x: round(x, ndigits=3)
  32. >>> f = compose(round_three, int.__truediv__)
  33. >>> [f(3*x, x+1) for x in range(1,10)]
  34. [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]
  35. """
  36. def compose_two(f1, f2):
  37. return lambda *args, **kwargs: f1(f2(*args, **kwargs))
  38. return functools.reduce(compose_two, funcs)
  39. def method_caller(method_name, *args, **kwargs):
  40. """
  41. Return a function that will call a named method on the
  42. target object with optional positional and keyword
  43. arguments.
  44. >>> lower = method_caller('lower')
  45. >>> lower('MyString')
  46. 'mystring'
  47. """
  48. def call_method(target):
  49. func = getattr(target, method_name)
  50. return func(*args, **kwargs)
  51. return call_method
  52. def once(func):
  53. """
  54. Decorate func so it's only ever called the first time.
  55. This decorator can ensure that an expensive or non-idempotent function
  56. will not be expensive on subsequent calls and is idempotent.
  57. >>> add_three = once(lambda a: a+3)
  58. >>> add_three(3)
  59. 6
  60. >>> add_three(9)
  61. 6
  62. >>> add_three('12')
  63. 6
  64. To reset the stored value, simply clear the property ``saved_result``.
  65. >>> del add_three.saved_result
  66. >>> add_three(9)
  67. 12
  68. >>> add_three(8)
  69. 12
  70. Or invoke 'reset()' on it.
  71. >>> add_three.reset()
  72. >>> add_three(-3)
  73. 0
  74. >>> add_three(0)
  75. 0
  76. """
  77. @functools.wraps(func)
  78. def wrapper(*args, **kwargs):
  79. if not hasattr(wrapper, 'saved_result'):
  80. wrapper.saved_result = func(*args, **kwargs)
  81. return wrapper.saved_result
  82. wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')
  83. return wrapper
  84. def method_cache(method, cache_wrapper=None):
  85. """
  86. Wrap lru_cache to support storing the cache data in the object instances.
  87. Abstracts the common paradigm where the method explicitly saves an
  88. underscore-prefixed protected property on first call and returns that
  89. subsequently.
  90. >>> class MyClass:
  91. ... calls = 0
  92. ...
  93. ... @method_cache
  94. ... def method(self, value):
  95. ... self.calls += 1
  96. ... return value
  97. >>> a = MyClass()
  98. >>> a.method(3)
  99. 3
  100. >>> for x in range(75):
  101. ... res = a.method(x)
  102. >>> a.calls
  103. 75
  104. Note that the apparent behavior will be exactly like that of lru_cache
  105. except that the cache is stored on each instance, so values in one
  106. instance will not flush values from another, and when an instance is
  107. deleted, so are the cached values for that instance.
  108. >>> b = MyClass()
  109. >>> for x in range(35):
  110. ... res = b.method(x)
  111. >>> b.calls
  112. 35
  113. >>> a.method(0)
  114. 0
  115. >>> a.calls
  116. 75
  117. Note that if method had been decorated with ``functools.lru_cache()``,
  118. a.calls would have been 76 (due to the cached value of 0 having been
  119. flushed by the 'b' instance).
  120. Clear the cache with ``.cache_clear()``
  121. >>> a.method.cache_clear()
  122. Another cache wrapper may be supplied:
  123. >>> cache = lru_cache(maxsize=2)
  124. >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
  125. >>> a = MyClass()
  126. >>> a.method2()
  127. 3
  128. Caution - do not subsequently wrap the method with another decorator, such
  129. as ``@property``, which changes the semantics of the function.
  130. See also
  131. http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
  132. for another implementation and additional justification.
  133. """
  134. cache_wrapper = cache_wrapper or lru_cache()
  135. def wrapper(self, *args, **kwargs):
  136. # it's the first call, replace the method with a cached, bound method
  137. bound_method = functools.partial(method, self)
  138. cached_method = cache_wrapper(bound_method)
  139. setattr(self, method.__name__, cached_method)
  140. return cached_method(*args, **kwargs)
  141. return _special_method_cache(method, cache_wrapper) or wrapper
  142. def _special_method_cache(method, cache_wrapper):
  143. """
  144. Because Python treats special methods differently, it's not
  145. possible to use instance attributes to implement the cached
  146. methods.
  147. Instead, install the wrapper method under a different name
  148. and return a simple proxy to that wrapper.
  149. https://github.com/jaraco/jaraco.functools/issues/5
  150. """
  151. name = method.__name__
  152. special_names = '__getattr__', '__getitem__'
  153. if name not in special_names:
  154. return
  155. wrapper_name = '__cached' + name
  156. def proxy(self, *args, **kwargs):
  157. if wrapper_name not in vars(self):
  158. bound = functools.partial(method, self)
  159. cache = cache_wrapper(bound)
  160. setattr(self, wrapper_name, cache)
  161. else:
  162. cache = getattr(self, wrapper_name)
  163. return cache(*args, **kwargs)
  164. return proxy
  165. def apply(transform):
  166. """
  167. Decorate a function with a transform function that is
  168. invoked on results returned from the decorated function.
  169. >>> @apply(reversed)
  170. ... def get_numbers(start):
  171. ... return range(start, start+3)
  172. >>> list(get_numbers(4))
  173. [6, 5, 4]
  174. """
  175. def wrap(func):
  176. return compose(transform, func)
  177. return wrap
  178. def result_invoke(action):
  179. r"""
  180. Decorate a function with an action function that is
  181. invoked on the results returned from the decorated
  182. function (for its side-effect), then return the original
  183. result.
  184. >>> @result_invoke(print)
  185. ... def add_two(a, b):
  186. ... return a + b
  187. >>> x = add_two(2, 3)
  188. 5
  189. """
  190. def wrap(func):
  191. @functools.wraps(func)
  192. def wrapper(*args, **kwargs):
  193. result = func(*args, **kwargs)
  194. action(result)
  195. return result
  196. return wrapper
  197. return wrap
  198. def call_aside(f, *args, **kwargs):
  199. """
  200. Call a function for its side effect after initialization.
  201. >>> @call_aside
  202. ... def func(): print("called")
  203. called
  204. >>> func()
  205. called
  206. Use functools.partial to pass parameters to the initial call
  207. >>> @functools.partial(call_aside, name='bingo')
  208. ... def func(name): print("called with", name)
  209. called with bingo
  210. """
  211. f(*args, **kwargs)
  212. return f
  213. class Throttler:
  214. """
  215. Rate-limit a function (or other callable)
  216. """
  217. def __init__(self, func, max_rate=float('Inf')):
  218. if isinstance(func, Throttler):
  219. func = func.func
  220. self.func = func
  221. self.max_rate = max_rate
  222. self.reset()
  223. def reset(self):
  224. self.last_called = 0
  225. def __call__(self, *args, **kwargs):
  226. self._wait()
  227. return self.func(*args, **kwargs)
  228. def _wait(self):
  229. "ensure at least 1/max_rate seconds from last call"
  230. elapsed = time.time() - self.last_called
  231. must_wait = 1 / self.max_rate - elapsed
  232. time.sleep(max(0, must_wait))
  233. self.last_called = time.time()
  234. def __get__(self, obj, type=None):
  235. return first_invoke(self._wait, functools.partial(self.func, obj))
  236. def first_invoke(func1, func2):
  237. """
  238. Return a function that when invoked will invoke func1 without
  239. any parameters (for its side-effect) and then invoke func2
  240. with whatever parameters were passed, returning its result.
  241. """
  242. def wrapper(*args, **kwargs):
  243. func1()
  244. return func2(*args, **kwargs)
  245. return wrapper
  246. def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
  247. """
  248. Given a callable func, trap the indicated exceptions
  249. for up to 'retries' times, invoking cleanup on the
  250. exception. On the final attempt, allow any exceptions
  251. to propagate.
  252. """
  253. attempts = count() if retries == float('inf') else range(retries)
  254. for attempt in attempts:
  255. try:
  256. return func()
  257. except trap:
  258. cleanup()
  259. return func()
  260. def retry(*r_args, **r_kwargs):
  261. """
  262. Decorator wrapper for retry_call. Accepts arguments to retry_call
  263. except func and then returns a decorator for the decorated function.
  264. Ex:
  265. >>> @retry(retries=3)
  266. ... def my_func(a, b):
  267. ... "this is my funk"
  268. ... print(a, b)
  269. >>> my_func.__doc__
  270. 'this is my funk'
  271. """
  272. def decorate(func):
  273. @functools.wraps(func)
  274. def wrapper(*f_args, **f_kwargs):
  275. bound = functools.partial(func, *f_args, **f_kwargs)
  276. return retry_call(bound, *r_args, **r_kwargs)
  277. return wrapper
  278. return decorate
  279. def print_yielded(func):
  280. """
  281. Convert a generator into a function that prints all yielded elements
  282. >>> @print_yielded
  283. ... def x():
  284. ... yield 3; yield None
  285. >>> x()
  286. 3
  287. None
  288. """
  289. print_all = functools.partial(map, print)
  290. print_results = compose(more_itertools.recipes.consume, print_all, func)
  291. return functools.wraps(func)(print_results)
  292. def pass_none(func):
  293. """
  294. Wrap func so it's not called if its first param is None
  295. >>> print_text = pass_none(print)
  296. >>> print_text('text')
  297. text
  298. >>> print_text(None)
  299. """
  300. @functools.wraps(func)
  301. def wrapper(param, *args, **kwargs):
  302. if param is not None:
  303. return func(param, *args, **kwargs)
  304. return wrapper
  305. def assign_params(func, namespace):
  306. """
  307. Assign parameters from namespace where func solicits.
  308. >>> def func(x, y=3):
  309. ... print(x, y)
  310. >>> assigned = assign_params(func, dict(x=2, z=4))
  311. >>> assigned()
  312. 2 3
  313. The usual errors are raised if a function doesn't receive
  314. its required parameters:
  315. >>> assigned = assign_params(func, dict(y=3, z=4))
  316. >>> assigned()
  317. Traceback (most recent call last):
  318. TypeError: func() ...argument...
  319. It even works on methods:
  320. >>> class Handler:
  321. ... def meth(self, arg):
  322. ... print(arg)
  323. >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()
  324. crystal
  325. """
  326. try:
  327. sig = inspect.signature(func)
  328. params = sig.parameters.keys()
  329. except AttributeError:
  330. spec = inspect.getargspec(func)
  331. params = spec.args
  332. call_ns = {
  333. k: namespace[k]
  334. for k in params
  335. if k in namespace
  336. }
  337. return functools.partial(func, **call_ns)
  338. def save_method_args(method):
  339. """
  340. Wrap a method such that when it is called, the args and kwargs are
  341. saved on the method.
  342. >>> class MyClass:
  343. ... @save_method_args
  344. ... def method(self, a, b):
  345. ... print(a, b)
  346. >>> my_ob = MyClass()
  347. >>> my_ob.method(1, 2)
  348. 1 2
  349. >>> my_ob._saved_method.args
  350. (1, 2)
  351. >>> my_ob._saved_method.kwargs
  352. {}
  353. >>> my_ob.method(a=3, b='foo')
  354. 3 foo
  355. >>> my_ob._saved_method.args
  356. ()
  357. >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
  358. True
  359. The arguments are stored on the instance, allowing for
  360. different instance to save different args.
  361. >>> your_ob = MyClass()
  362. >>> your_ob.method({str('x'): 3}, b=[4])
  363. {'x': 3} [4]
  364. >>> your_ob._saved_method.args
  365. ({'x': 3},)
  366. >>> my_ob._saved_method.args
  367. ()
  368. """
  369. args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
  370. @functools.wraps(method)
  371. def wrapper(self, *args, **kwargs):
  372. attr_name = '_saved_' + method.__name__
  373. attr = args_and_kwargs(args, kwargs)
  374. setattr(self, attr_name, attr)
  375. return method(self, *args, **kwargs)
  376. return wrapper