1import functools
2import types
3from collections.abc import Callable
4from typing import TypeVar
5
6
7# from jaraco.functools 3.3
8def method_cache(method, cache_wrapper=None):
9 """
10 Wrap lru_cache to support storing the cache data in the object instances.
11
12 Abstracts the common paradigm where the method explicitly saves an
13 underscore-prefixed protected property on first call and returns that
14 subsequently.
15
16 >>> class MyClass:
17 ... calls = 0
18 ...
19 ... @method_cache
20 ... def method(self, value):
21 ... self.calls += 1
22 ... return value
23
24 >>> a = MyClass()
25 >>> a.method(3)
26 3
27 >>> for x in range(75):
28 ... res = a.method(x)
29 >>> a.calls
30 75
31
32 Note that the apparent behavior will be exactly like that of lru_cache
33 except that the cache is stored on each instance, so values in one
34 instance will not flush values from another, and when an instance is
35 deleted, so are the cached values for that instance.
36
37 >>> b = MyClass()
38 >>> for x in range(35):
39 ... res = b.method(x)
40 >>> b.calls
41 35
42 >>> a.method(0)
43 0
44 >>> a.calls
45 75
46
47 Note that if method had been decorated with ``functools.lru_cache()``,
48 a.calls would have been 76 (due to the cached value of 0 having been
49 flushed by the 'b' instance).
50
51 Clear the cache with ``.cache_clear()``
52
53 >>> a.method.cache_clear()
54
55 Same for a method that hasn't yet been called.
56
57 >>> c = MyClass()
58 >>> c.method.cache_clear()
59
60 Another cache wrapper may be supplied:
61
62 >>> cache = functools.lru_cache(maxsize=2)
63 >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
64 >>> a = MyClass()
65 >>> a.method2()
66 3
67
68 Caution - do not subsequently wrap the method with another decorator, such
69 as ``@property``, which changes the semantics of the function.
70
71 See also
72 http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
73 for another implementation and additional justification.
74 """
75 cache_wrapper = cache_wrapper or functools.lru_cache()
76
77 def wrapper(self, *args, **kwargs):
78 # it's the first call, replace the method with a cached, bound method
79 bound_method = types.MethodType(method, self)
80 cached_method = cache_wrapper(bound_method)
81 setattr(self, method.__name__, cached_method)
82 return cached_method(*args, **kwargs)
83
84 # Support cache clear even before cache has been created.
85 wrapper.cache_clear = lambda: None
86
87 return wrapper
88
89
90# From jaraco.functools 3.3
91def pass_none(func):
92 """
93 Wrap func so it's not called if its first param is None
94
95 >>> print_text = pass_none(print)
96 >>> print_text('text')
97 text
98 >>> print_text(None)
99 """
100
101 @functools.wraps(func)
102 def wrapper(param, *args, **kwargs):
103 if param is not None:
104 return func(param, *args, **kwargs)
105
106 return wrapper
107
108
109# From jaraco.functools 4.0.2
110def compose(*funcs):
111 """
112 Compose any number of unary functions into a single unary function.
113
114 Comparable to
115 `function composition <https://en.wikipedia.org/wiki/Function_composition>`_
116 in mathematics:
117
118 ``h = g ∘ f`` implies ``h(x) = g(f(x))``.
119
120 In Python, ``h = compose(g, f)``.
121
122 >>> import textwrap
123 >>> expected = str.strip(textwrap.dedent(compose.__doc__))
124 >>> strip_and_dedent = compose(str.strip, textwrap.dedent)
125 >>> strip_and_dedent(compose.__doc__) == expected
126 True
127
128 Compose also allows the innermost function to take arbitrary arguments.
129
130 >>> round_three = lambda x: round(x, ndigits=3)
131 >>> f = compose(round_three, int.__truediv__)
132 >>> [f(3*x, x+1) for x in range(1,10)]
133 [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]
134 """
135
136 def compose_two(f1, f2):
137 return lambda *args, **kwargs: f1(f2(*args, **kwargs))
138
139 return functools.reduce(compose_two, funcs)
140
141
142def apply(transform):
143 """
144 Decorate a function with a transform function that is
145 invoked on results returned from the decorated function.
146
147 >>> @apply(reversed)
148 ... def get_numbers(start):
149 ... "doc for get_numbers"
150 ... return range(start, start+3)
151 >>> list(get_numbers(4))
152 [6, 5, 4]
153 >>> get_numbers.__doc__
154 'doc for get_numbers'
155 """
156
157 def wrap(func):
158 return functools.wraps(func)(compose(transform, func))
159
160 return wrap
161
162
163# From jaraco.functools 4.4
164def noop(*args, **kwargs):
165 """
166 A no-operation function that does nothing.
167
168 >>> noop(1, 2, three=3)
169 """
170
171
172_T = TypeVar('_T')
173
174
175# From jaraco.functools 4.4
176def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]:
177 """
178 Wrap the function to always return the first parameter.
179
180 >>> passthrough(print)('3')
181 3
182 '3'
183 """
184
185 @functools.wraps(func)
186 def wrapper(first: _T, *args, **kwargs) -> _T:
187 func(first, *args, **kwargs)
188 return first
189
190 return wrapper # type: ignore[return-value]