functools.py 13 KB

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