functools.py 15 KB

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