Debian Codegraph @

jaraco/functools/__init__.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import collections.abc
4 import functools
5 import inspect
6 import itertools
7 import operator
8 import time
9 import types
10 import warnings
11
12 from typing import Callable, TypeVar
13
14 import more_itertools
15
16
17 def compose(*funcs):
18 """
19 Compose any number of unary functions into a single unary function.
20
21 Comparable to
22 `function composition <https://en.wikipedia.org/wiki/Function_composition>`_
23 in mathematics:
24
25 ``h = g ∘ f`` implies ``h(x) = g(f(x))``.
26
27 In Python, ``h = compose(g, f)``.
28
29 >>> import textwrap
30 >>> expected = str.strip(textwrap.dedent(compose.__doc__))
31 >>> strip_and_dedent = compose(str.strip, textwrap.dedent)
32 >>> strip_and_dedent(compose.__doc__) == expected
33 True
34
35 Compose also allows the innermost function to take arbitrary arguments.
36
37 >>> round_three = lambda x: round(x, ndigits=3)
38 >>> f = compose(round_three, int.__truediv__)
39 >>> [f(3*x, x+1) for x in range(1,10)]
40 [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]
41 """
42
43 def compose_two(f1, f2):
44 return lambda *args, **kwargs: f1(f2(*args, **kwargs))
45
46 return functools.reduce(compose_two, funcs)
47
48
49 def once(func):
50 """
51 Decorate func so it's only ever called the first time.
52
53 This decorator can ensure that an expensive or non-idempotent function
54 will not be expensive on subsequent calls and is idempotent.
55
56 >>> add_three = once(lambda a: a+3)
57 >>> add_three(3)
58 6
59 >>> add_three(9)
60 6
61 >>> add_three('12')
62 6
63
64 To reset the stored value, simply clear the property ``saved_result``.
65
66 >>> del add_three.saved_result
67 >>> add_three(9)
68 12
69 >>> add_three(8)
70 12
71
72 Or invoke 'reset()' on it.
73
74 >>> add_three.reset()
75 >>> add_three(-3)
76 0
77 >>> add_three(0)
78 0
79 """
80
81 @functools.wraps(func)
82 def wrapper(*args, **kwargs):
83 if not hasattr(wrapper, 'saved_result'):
84 wrapper.saved_result = func(*args, **kwargs)
85 return wrapper.saved_result
86
87 wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')
88 return wrapper
89
90
91 def method_cache(method, cache_wrapper=functools.lru_cache()):
92 """
93 Wrap lru_cache to support storing the cache data in the object instances.
94
95 Abstracts the common paradigm where the method explicitly saves an
96 underscore-prefixed protected property on first call and returns that
97 subsequently.
98
99 >>> class MyClass:
100 ... calls = 0
101 ...
102 ... @method_cache
103 ... def method(self, value):
104 ... self.calls += 1
105 ... return value
106
107 >>> a = MyClass()
108 >>> a.method(3)
109 3
110 >>> for x in range(75):
111 ... res = a.method(x)
112 >>> a.calls
113 75
114
115 Note that the apparent behavior will be exactly like that of lru_cache
116 except that the cache is stored on each instance, so values in one
117 instance will not flush values from another, and when an instance is
118 deleted, so are the cached values for that instance.
119
120 >>> b = MyClass()
121 >>> for x in range(35):
122 ... res = b.method(x)
123 >>> b.calls
124 35
125 >>> a.method(0)
126 0
127 >>> a.calls
128 75
129
130 Note that if method had been decorated with ``functools.lru_cache()``,
131 a.calls would have been 76 (due to the cached value of 0 having been
132 flushed by the 'b' instance).
133
134 Clear the cache with ``.cache_clear()``
135
136 >>> a.method.cache_clear()
137
138 Same for a method that hasn't yet been called.
139
140 >>> c = MyClass()
141 >>> c.method.cache_clear()
142
143 Another cache wrapper may be supplied:
144
145 >>> cache = functools.lru_cache(maxsize=2)
146 >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
147 >>> a = MyClass()
148 >>> a.method2()
149 3
150
151 Caution - do not subsequently wrap the method with another decorator, such
152 as ``@property``, which changes the semantics of the function.
153
154 See also
155 http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
156 for another implementation and additional justification.
157 """
158
159 def wrapper(self, *args, **kwargs):
160 # it's the first call, replace the method with a cached, bound method
161 bound_method = types.MethodType(method, self)
162 cached_method = cache_wrapper(bound_method)
163 setattr(self, method.__name__, cached_method)
164 return cached_method(*args, **kwargs)
165
166 # Support cache clear even before cache has been created.
167 wrapper.cache_clear = lambda: None
168
169 return _special_method_cache(method, cache_wrapper) or wrapper
170
171
172 def _special_method_cache(method, cache_wrapper):
173 """
174 Because Python treats special methods differently, it's not
175 possible to use instance attributes to implement the cached
176 methods.
177
178 Instead, install the wrapper method under a different name
179 and return a simple proxy to that wrapper.
180
181 https://github.com/jaraco/jaraco.functools/issues/5
182 """
183 name = method.__name__
184 special_names = '__getattr__', '__getitem__'
185
186 if name not in special_names:
187 return None
188
189 wrapper_name = '__cached' + name
190
191 def proxy(self, /, *args, **kwargs):
192 if wrapper_name not in vars(self):
193 bound = types.MethodType(method, self)
194 cache = cache_wrapper(bound)
195 setattr(self, wrapper_name, cache)
196 else:
197 cache = getattr(self, wrapper_name)
198 return cache(*args, **kwargs)
199
200 return proxy
201
202
203 def apply(transform):
204 """
205 Decorate a function with a transform function that is
206 invoked on results returned from the decorated function.
207
208 >>> @apply(reversed)
209 ... def get_numbers(start):
210 ... "doc for get_numbers"
211 ... return range(start, start+3)
212 >>> list(get_numbers(4))
213 [6, 5, 4]
214 >>> get_numbers.__doc__
215 'doc for get_numbers'
216 """
217
218 def wrap(func):
219 return functools.wraps(func)(compose(transform, func))
220
221 return wrap
222
223
224 def result_invoke(action):
225 r"""
226 Decorate a function with an action function that is
227 invoked on the results returned from the decorated
228 function (for its side effect), then return the original
229 result.
230
231 >>> @result_invoke(print)
232 ... def add_two(a, b):
233 ... return a + b
234 >>> x = add_two(2, 3)
235 5
236 >>> x
237 5
238 """
239
240 def wrap(func):
241 @functools.wraps(func)
242 def wrapper(*args, **kwargs):
243 result = func(*args, **kwargs)
244 action(result)
245 return result
246
247 return wrapper
248
249 return wrap
250
251
252 def invoke(f, /, *args, **kwargs):
253 """
254 Call a function for its side effect after initialization.
255
256 The benefit of using the decorator instead of simply invoking a function
257 after defining it is that it makes explicit the author's intent for the
258 function to be called immediately. Whereas if one simply calls the
259 function immediately, it's less obvious if that was intentional or
260 incidental. It also avoids repeating the name - the two actions, defining
261 the function and calling it immediately are modeled separately, but linked
262 by the decorator construct.
263
264 The benefit of having a function construct (opposed to just invoking some
265 behavior inline) is to serve as a scope in which the behavior occurs. It
266 avoids polluting the global namespace with local variables, provides an
267 anchor on which to attach documentation (docstring), keeps the behavior
268 logically separated (instead of conceptually separated or not separated at
269 all), and provides potential to re-use the behavior for testing or other
270 purposes.
271
272 This function is named as a pithy way to communicate, "call this function
273 primarily for its side effect", or "while defining this function, also
274 take it aside and call it". It exists because there's no Python construct
275 for "define and call" (nor should there be, as decorators serve this need
276 just fine). The behavior happens immediately and synchronously.
277
278 >>> @invoke
279 ... def func(): print("called")
280 called
281 >>> func()
282 called
283
284 Use functools.partial to pass parameters to the initial call
285
286 >>> @functools.partial(invoke, name='bingo')
287 ... def func(name): print('called with', name)
288 called with bingo
289 """
290 f(*args, **kwargs)
291 return f
292
293
294 class Throttler:
295 """Rate-limit a function (or other callable)."""
296
297 def __init__(self, func, max_rate=float('Inf')):
298 if isinstance(func, Throttler):
299 func = func.func
300 self.func = func
301 self.max_rate = max_rate
302 self.reset()
303
304 def reset(self):
305 self.last_called = 0
306
307 def __call__(self, *args, **kwargs):
308 self._wait()
309 return self.func(*args, **kwargs)
310
311 def _wait(self):
312 """Ensure at least 1/max_rate seconds from last call."""
313 elapsed = time.time() - self.last_called
314 must_wait = 1 / self.max_rate - elapsed
315 time.sleep(max(0, must_wait))
316 self.last_called = time.time()
317
318 def __get__(self, obj, owner=None):
319 return first_invoke(self._wait, functools.partial(self.func, obj))
320
321
322 def first_invoke(func1, func2):
323 """
324 Return a function that when invoked will invoke func1 without
325 any parameters (for its side effect) and then invoke func2
326 with whatever parameters were passed, returning its result.
327 """
328
329 def wrapper(*args, **kwargs):
330 func1()
331 return func2(*args, **kwargs)
332
333 return wrapper
334
335
336 method_caller = first_invoke(
337 lambda: warnings.warn(
338 '`jaraco.functools.method_caller` is deprecated, '
339 'use `operator.methodcaller` instead',
340 DeprecationWarning,
341 stacklevel=3,
342 ),
343 operator.methodcaller,
344 )
345
346
347 def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
348 """
349 Given a callable func, trap the indicated exceptions
350 for up to 'retries' times, invoking cleanup on the
351 exception. On the final attempt, allow any exceptions
352 to propagate.
353 """
354 attempts = itertools.count() if retries == float('inf') else range(retries)
355 for _ in attempts:
356 try:
357 return func()
358 except trap:
359 cleanup()
360
361 return func()
362
363
364 def retry(*r_args, **r_kwargs):
365 """
366 Decorator wrapper for retry_call. Accepts arguments to retry_call
367 except func and then returns a decorator for the decorated function.
368
369 Ex:
370
371 >>> @retry(retries=3)
372 ... def my_func(a, b):
373 ... "this is my funk"
374 ... print(a, b)
375 >>> my_func.__doc__
376 'this is my funk'
377 """
378
379 def decorate(func):
380 @functools.wraps(func)
381 def wrapper(*f_args, **f_kwargs):
382 bound = functools.partial(func, *f_args, **f_kwargs)
383 return retry_call(bound, *r_args, **r_kwargs)
384
385 return wrapper
386
387 return decorate
388
389
390 def print_yielded(func):
391 """
392 Convert a generator into a function that prints all yielded elements.
393
394 >>> @print_yielded
395 ... def x():
396 ... yield 3; yield None
397 >>> x()
398 3
399 None
400 """
401 print_all = functools.partial(map, print)
402 print_results = compose(more_itertools.consume, print_all, func)
403 return functools.wraps(func)(print_results)
404
405
406 def pass_none(func):
407 """
408 Wrap func so it's not called if its first param is None.
409
410 >>> print_text = pass_none(print)
411 >>> print_text('text')
412 text
413 >>> print_text(None)
414 """
415
416 @functools.wraps(func)
417 def wrapper(param, /, *args, **kwargs):
418 if param is not None:
419 return func(param, *args, **kwargs)
420 return None
421
422 return wrapper
423
424
425 def assign_params(func, namespace):
426 """
427 Assign parameters from namespace where func solicits.
428
429 >>> def func(x, y=3):
430 ... print(x, y)
431 >>> assigned = assign_params(func, dict(x=2, z=4))
432 >>> assigned()
433 2 3
434
435 The usual errors are raised if a function doesn't receive
436 its required parameters:
437
438 >>> assigned = assign_params(func, dict(y=3, z=4))
439 >>> assigned()
440 Traceback (most recent call last):
441 TypeError: func() ...argument...
442
443 It even works on methods:
444
445 >>> class Handler:
446 ... def meth(self, arg):
447 ... print(arg)
448 >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()
449 crystal
450 """
451 sig = inspect.signature(func)
452 params = sig.parameters.keys()
453 call_ns = {k: namespace[k] for k in params if k in namespace}
454 return functools.partial(func, **call_ns)
455
456
457 def save_method_args(method):
458 """
459 Wrap a method such that when it is called, the args and kwargs are
460 saved on the method.
461
462 >>> class MyClass:
463 ... @save_method_args
464 ... def method(self, a, b):
465 ... print(a, b)
466 >>> my_ob = MyClass()
467 >>> my_ob.method(1, 2)
468 1 2
469 >>> my_ob._saved_method.args
470 (1, 2)
471 >>> my_ob._saved_method.kwargs
472 {}
473 >>> my_ob.method(a=3, b='foo')
474 3 foo
475 >>> my_ob._saved_method.args
476 ()
477 >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')
478 True
479
480 The arguments are stored on the instance, allowing for
481 different instance to save different args.
482
483 >>> your_ob = MyClass()
484 >>> your_ob.method({str('x'): 3}, b=[4])
485 {'x': 3} [4]
486 >>> your_ob._saved_method.args
487 ({'x': 3},)
488 >>> my_ob._saved_method.args
489 ()
490 """
491 args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')
492
493 @functools.wraps(method)
494 def wrapper(self, /, *args, **kwargs):
495 attr_name = '_saved_' + method.__name__
496 attr = args_and_kwargs(args, kwargs)
497 setattr(self, attr_name, attr)
498 return method(self, *args, **kwargs)
499
500 return wrapper
501
502
503 def except_(*exceptions, replace=None, use=None):
504 """
505 Replace the indicated exceptions, if raised, with the indicated
506 literal replacement or evaluated expression (if present).
507
508 >>> safe_int = except_(ValueError)(int)
509 >>> safe_int('five')
510 >>> safe_int('5')
511 5
512
513 Specify a literal replacement with ``replace``.
514
515 >>> safe_int_r = except_(ValueError, replace=0)(int)
516 >>> safe_int_r('five')
517 0
518
519 Provide an expression to ``use`` to pass through particular parameters.
520
521 >>> safe_int_pt = except_(ValueError, use='args[0]')(int)
522 >>> safe_int_pt('five')
523 'five'
524
525 """
526
527 def decorate(func):
528 @functools.wraps(func)
529 def wrapper(*args, **kwargs):
530 try:
531 return func(*args, **kwargs)
532 except exceptions:
533 try:
534 return eval(use)
535 except TypeError:
536 return replace
537
538 return wrapper
539
540 return decorate
541
542
543 def identity(x):
544 """
545 Return the argument.
546
547 >>> o = object()
548 >>> identity(o) is o
549 True
550 """
551 return x
552
553
554 def bypass_when(check, *, _op=identity):
555 """
556 Decorate a function to return its parameter when ``check``.
557
558 >>> bypassed = [] # False
559
560 >>> @bypass_when(bypassed)
561 ... def double(x):
562 ... return x * 2
563 >>> double(2)
564 4
565 >>> bypassed[:] = [object()] # True
566 >>> double(2)
567 2
568 """
569
570 def decorate(func):
571 @functools.wraps(func)
572 def wrapper(param, /):
573 return param if _op(check) else func(param)
574
575 return wrapper
576
577 return decorate
578
579
580 def bypass_unless(check):
581 """
582 Decorate a function to return its parameter unless ``check``.
583
584 >>> enabled = [object()] # True
585
586 >>> @bypass_unless(enabled)
587 ... def double(x):
588 ... return x * 2
589 >>> double(2)
590 4
591 >>> del enabled[:] # False
592 >>> double(2)
593 2
594 """
595 return bypass_when(check, _op=operator.not_)
596
597
598 @functools.singledispatch
599 def _splat_inner(args, func):
600 """Splat args to func."""
601 return func(*args)
602
603
604 @_splat_inner.register
605 def _(args: collections.abc.Mapping, func):
606 """Splat kargs to func as kwargs."""
607 return func(**args)
608
609
610 def splat(func):
611 """
612 Wrap func to expect its parameters to be passed positionally in a tuple.
613
614 Has a similar effect to that of ``itertools.starmap`` over
615 simple ``map``.
616
617 >>> pairs = [(-1, 1), (0, 2)]
618 >>> more_itertools.consume(itertools.starmap(print, pairs))
619 -1 1
620 0 2
621 >>> more_itertools.consume(map(splat(print), pairs))
622 -1 1
623 0 2
624
625 The approach generalizes to other iterators that don't have a "star"
626 equivalent, such as a "starfilter".
627
628 >>> list(filter(splat(operator.add), pairs))
629 [(0, 2)]
630
631 Splat also accepts a mapping argument.
632
633 >>> def is_nice(msg, code):
634 ... return "smile" in msg or code == 0
635 >>> msgs = [
636 ... dict(msg='smile!', code=20),
637 ... dict(msg='error :(', code=1),
638 ... dict(msg='unknown', code=0),
639 ... ]
640 >>> for msg in filter(splat(is_nice), msgs):
641 ... print(msg)
642 {'msg': 'smile!', 'code': 20}
643 {'msg': 'unknown', 'code': 0}
644 """
645 return functools.wraps(func)(functools.partial(_splat_inner, func=func))
646
647
648 _T = TypeVar('_T')
649
650
651 def chainable(method: Callable[[_T, ...], None]) -> Callable[[_T, ...], _T]:
652 """
653 Wrap an instance method to always return self.
654
655
656 >>> class Dingus:
657 ... @chainable
658 ... def set_attr(self, name, val):
659 ... setattr(self, name, val)
660 >>> d = Dingus().set_attr('a', 'eh!')
661 >>> d.a
662 'eh!'
663 >>> d2 = Dingus().set_attr('a', 'eh!').set_attr('b', 'bee!')
664 >>> d2.a + d2.b
665 'eh!bee!'
666
667 Enforces that the return value is null.
668
669 >>> class BorkedDingus:
670 ... @chainable
671 ... def set_attr(self, name, val):
672 ... setattr(self, name, val)
673 ... return len(name)
674 >>> BorkedDingus().set_attr('a', 'eh!')
675 Traceback (most recent call last):
676 ...
677 AssertionError
678 """
679
680 @functools.wraps(method)
681 def wrapper(self, *args, **kwargs):
682 assert method(self, *args, **kwargs) is None
683 return self
684
685 return wrapper