Debian Codegraph @

src/cachetools/_cachedmethod.py

raw
1 """Method decorator helpers."""
2
3 __all__ = ()
4
5 import functools
6 import warnings
7 import weakref
8
9
10 def _warn_classmethod(stacklevel):
11 warnings.warn(
12 "decorating class methods with @cachedmethod is deprecated",
13 DeprecationWarning,
14 stacklevel=stacklevel,
15 )
16
17
18 def _warn_instance_dict(msg, stacklevel):
19 warnings.warn(
20 msg,
21 DeprecationWarning,
22 stacklevel=stacklevel,
23 )
24
25
26 class _WrapperBase:
27 """Wrapper base class providing default implementations for properties."""
28
29 def __init__(self, obj, method, cache, key, lock=None, cond=None):
30 if isinstance(obj, type):
31 _warn_classmethod(stacklevel=5)
32 functools.update_wrapper(self, method)
33 self._obj = obj # protected
34 self.__cache = cache
35 self.__key = key
36 self.__lock = lock
37 self.__cond = cond
38
39 def __call__(self, *args, **kwargs):
40 raise NotImplementedError() # pragma: no cover
41
42 def cache_clear(self):
43 raise NotImplementedError() # pragma: no cover
44
45 @property
46 def cache(self):
47 return self.__cache(self._obj)
48
49 @property
50 def cache_key(self):
51 return self.__key
52
53 @property
54 def cache_lock(self):
55 return None if self.__lock is None else self.__lock(self._obj)
56
57 @property
58 def cache_condition(self):
59 return None if self.__cond is None else self.__cond(self._obj)
60
61
62 class _DescriptorBase:
63 """Descriptor base class implementing the basic descriptor protocol."""
64
65 def __init__(self, deprecated=False):
66 self.__attrname = None
67 self.__deprecated = deprecated
68
69 def __set_name__(self, owner, name):
70 if self.__attrname is None:
71 self.__attrname = name
72 elif name != self.__attrname:
73 raise TypeError(
74 "Cannot assign the same @cachedmethod to two different names "
75 f"({self.__attrname!r} and {name!r})."
76 )
77
78 def __get__(self, obj, objtype=None):
79 wrapper = self.Wrapper(obj)
80 if self.__attrname is not None:
81 # replace descriptor instance with wrapper in instance dict
82 try:
83 # In case of a race condition where another thread already replaced
84 # the descriptor, prefer the initial wrapper.
85 wrapper = obj.__dict__.setdefault(self.__attrname, wrapper)
86 except AttributeError:
87 # not all objects have __dict__ (e.g. class defines slots)
88 msg = (
89 f"No '__dict__' attribute on {type(obj).__name__!r} "
90 f"instance to cache {self.__attrname!r} property."
91 )
92 if self.__deprecated:
93 _warn_instance_dict(msg, 3)
94 else:
95 raise TypeError(msg) from None
96 except TypeError:
97 msg = (
98 f"The '__dict__' attribute on {type(obj).__name__!r} "
99 f"instance does not support item assignment for "
100 f"caching {self.__attrname!r} property."
101 )
102 if self.__deprecated:
103 _warn_instance_dict(msg, 3)
104 else:
105 raise TypeError(msg) from None
106 elif self.__deprecated:
107 pass # deprecated @classmethod, warning already raised elsewhere
108 else:
109 msg = "Cannot use @cachedmethod instance without calling __set_name__ on it"
110 raise TypeError(msg) from None
111 return wrapper
112
113
114 class _DeprecatedDescriptorBase(_DescriptorBase):
115 """Descriptor base class supporting deprecated @classmethod use."""
116
117 def __init__(self, wrapper, cache_clear):
118 super().__init__(deprecated=True)
119 self.__wrapper = wrapper
120 self.__cache_clear = cache_clear
121
122 # called for @classmethod with Python >= 3.13
123 def __call__(self, *args, **kwargs):
124 _warn_classmethod(stacklevel=3)
125 return self.__wrapper(*args, **kwargs)
126
127 # backward-compatible @classmethod handling with Python >= 3.13
128 def cache_clear(self, objtype):
129 _warn_classmethod(stacklevel=3)
130 return self.__cache_clear(objtype)
131
132
133 # At least for now, the implementation prefers clarity and performance
134 # over ease of maintenance, thus providing separate descriptors for
135 # all valid combinations of decorator parameters lock, condition and
136 # info.
137
138
139 def _condition_info(method, cache, key, lock, cond, info):
140 class Descriptor(_DescriptorBase):
141 class Wrapper(_WrapperBase):
142 def __init__(self, obj):
143 super().__init__(obj, method, cache, key, lock, cond)
144 self.__hits = self.__misses = 0
145 self.__pending = set()
146
147 def __call__(self, *args, **kwargs):
148 cache = self.cache
149 lock = self.cache_lock
150 cond = self.cache_condition
151 key = self.cache_key(self._obj, *args, **kwargs)
152
153 with lock:
154 cond.wait_for(lambda: key not in self.__pending)
155 try:
156 result = cache[key]
157 self.__hits += 1
158 return result
159 except KeyError:
160 self.__pending.add(key)
161 self.__misses += 1
162 try:
163 val = method(self._obj, *args, **kwargs)
164 with lock:
165 try:
166 cache[key] = val
167 except ValueError:
168 pass # value too large
169 return val
170 finally:
171 with lock:
172 self.__pending.remove(key)
173 cond.notify_all()
174
175 def cache_clear(self):
176 with self.cache_lock:
177 self.cache.clear()
178 self.__hits = self.__misses = 0
179
180 def cache_info(self):
181 with self.cache_lock:
182 return info(self.cache, self.__hits, self.__misses)
183
184 return Descriptor()
185
186
187 def _locked_info(method, cache, key, lock, info):
188 class Descriptor(_DescriptorBase):
189 class Wrapper(_WrapperBase):
190 def __init__(self, obj):
191 super().__init__(obj, method, cache, key, lock)
192 self.__hits = self.__misses = 0
193
194 def __call__(self, *args, **kwargs):
195 cache = self.cache
196 lock = self.cache_lock
197 key = self.cache_key(self._obj, *args, **kwargs)
198 with lock:
199 try:
200 result = cache[key]
201 self.__hits += 1
202 return result
203 except KeyError:
204 self.__misses += 1
205 val = method(self._obj, *args, **kwargs)
206 with lock:
207 try:
208 # In case of a race condition, i.e. if another thread
209 # stored a value for this key while we were calling
210 # method(), prefer the cached value.
211 return cache.setdefault(key, val)
212 except ValueError:
213 return val # value too large
214
215 def cache_clear(self):
216 with self.cache_lock:
217 self.cache.clear()
218 self.__hits = self.__misses = 0
219
220 def cache_info(self):
221 with self.cache_lock:
222 return info(self.cache, self.__hits, self.__misses)
223
224 return Descriptor()
225
226
227 def _unlocked_info(method, cache, key, info):
228 class Descriptor(_DescriptorBase):
229 class Wrapper(_WrapperBase):
230 def __init__(self, obj):
231 super().__init__(obj, method, cache, key)
232 self.__hits = self.__misses = 0
233
234 def __call__(self, *args, **kwargs):
235 cache = self.cache
236 key = self.cache_key(self._obj, *args, **kwargs)
237 try:
238 result = cache[key]
239 self.__hits += 1
240 return result
241 except KeyError:
242 self.__misses += 1
243 val = method(self._obj, *args, **kwargs)
244 try:
245 cache[key] = val
246 except ValueError:
247 pass # value too large
248 return val
249
250 def cache_clear(self):
251 self.cache.clear()
252 self.__hits = self.__misses = 0
253
254 def cache_info(self):
255 return info(self.cache, self.__hits, self.__misses)
256
257 return Descriptor()
258
259
260 def _condition(method, cache, key, lock, cond):
261 # backward-compatible weakref dictionary for Python >= 3.13
262 pending = weakref.WeakKeyDictionary()
263
264 def wrapper(self, pending, *args, **kwargs):
265 c = cache(self)
266 k = key(self, *args, **kwargs)
267 with lock(self):
268 cond(self).wait_for(lambda: k not in pending)
269 try:
270 return c[k]
271 except KeyError:
272 pending.add(k)
273 try:
274 v = method(self, *args, **kwargs)
275 with lock(self):
276 try:
277 c[k] = v
278 except ValueError:
279 pass # value too large
280 return v
281 finally:
282 with lock(self):
283 pending.remove(k)
284 cond(self).notify_all()
285
286 def cache_clear(self):
287 c = cache(self)
288 with lock(self):
289 c.clear()
290
291 def classmethod_wrapper(self, *args, **kwargs):
292 p = pending.setdefault(self, set())
293 return wrapper(self, p, *args, **kwargs)
294
295 class Descriptor(_DeprecatedDescriptorBase):
296 class Wrapper(_WrapperBase):
297 def __init__(self, obj):
298 super().__init__(obj, method, cache, key, lock, cond)
299 self.__pending = set()
300
301 def __call__(self, *args, **kwargs):
302 return wrapper(self._obj, self.__pending, *args, **kwargs)
303
304 # objtype: backward-compatible @classmethod handling with Python < 3.13
305 def cache_clear(self, _objtype=None):
306 return cache_clear(self._obj)
307
308 return Descriptor(classmethod_wrapper, cache_clear)
309
310
311 def _locked(method, cache, key, lock):
312 def wrapper(self, *args, **kwargs):
313 c = cache(self)
314 k = key(self, *args, **kwargs)
315 with lock(self):
316 try:
317 return c[k]
318 except KeyError:
319 pass # key not found
320 v = method(self, *args, **kwargs)
321 with lock(self):
322 try:
323 # In case of a race condition, i.e. if another thread
324 # stored a value for this key while we were calling
325 # method(), prefer the cached value.
326 return c.setdefault(k, v)
327 except ValueError:
328 return v # value too large
329
330 def cache_clear(self):
331 c = cache(self)
332 with lock(self):
333 c.clear()
334
335 class Descriptor(_DeprecatedDescriptorBase):
336 class Wrapper(_WrapperBase):
337 def __init__(self, obj):
338 super().__init__(obj, method, cache, key, lock)
339
340 def __call__(self, *args, **kwargs):
341 return wrapper(self._obj, *args, **kwargs)
342
343 # objtype: backward-compatible @classmethod handling with Python < 3.13
344 def cache_clear(self, _objtype=None):
345 return cache_clear(self._obj)
346
347 return Descriptor(wrapper, cache_clear)
348
349
350 def _unlocked(method, cache, key):
351 def wrapper(self, *args, **kwargs):
352 c = cache(self)
353 k = key(self, *args, **kwargs)
354 try:
355 return c[k]
356 except KeyError:
357 pass # key not found
358 v = method(self, *args, **kwargs)
359 try:
360 c[k] = v
361 except ValueError:
362 pass # value too large
363 return v
364
365 def cache_clear(self):
366 c = cache(self)
367 c.clear()
368
369 class Descriptor(_DeprecatedDescriptorBase):
370 class Wrapper(_WrapperBase):
371 def __init__(self, obj):
372 super().__init__(obj, method, cache, key)
373
374 def __call__(self, *args, **kwargs):
375 return wrapper(self._obj, *args, **kwargs)
376
377 # objtype: backward-compatible @classmethod handling with Python < 3.13
378 def cache_clear(self, _objtype=None):
379 return cache_clear(self._obj)
380
381 return Descriptor(wrapper, cache_clear)
382
383
384 def _wrapper(method, cache, key, lock=None, cond=None, info=None):
385 if info is not None:
386 if cond is not None and lock is not None:
387 wrapper = _condition_info(method, cache, key, lock, cond, info)
388 elif cond is not None:
389 wrapper = _condition_info(method, cache, key, cond, cond, info)
390 elif lock is not None:
391 wrapper = _locked_info(method, cache, key, lock, info)
392 else:
393 wrapper = _unlocked_info(method, cache, key, info)
394 else:
395 if cond is not None and lock is not None:
396 wrapper = _condition(method, cache, key, lock, cond)
397 elif cond is not None:
398 wrapper = _condition(method, cache, key, cond, cond)
399 elif lock is not None:
400 wrapper = _locked(method, cache, key, lock)
401 else:
402 wrapper = _unlocked(method, cache, key)
403
404 # backward-compatible properties for deprecated @classmethod use
405 wrapper.cache = cache
406 wrapper.cache_key = key
407 wrapper.cache_lock = lock if lock is not None else cond
408 wrapper.cache_condition = cond
409
410 return functools.update_wrapper(wrapper, method)