cachetools 8.0.0__tar.gz → 8.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {cachetools-8.0.0 → cachetools-8.0.2}/CHANGELOG.rst +51 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/MANIFEST.in +1 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/PKG-INFO +1 -1
- {cachetools-8.0.0 → cachetools-8.0.2}/docs/index.rst +10 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/__init__.py +142 -36
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/__init__.pyi +2 -2
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/_cached.py +9 -3
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/_cachedmethod.py +4 -4
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/_decorator.py +0 -2
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/_descriptor.py +17 -12
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/func.py +2 -3
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools.egg-info/PKG-INFO +1 -1
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools.egg-info/SOURCES.txt +0 -1
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/__init__.py +160 -4
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_cached.py +12 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_cachedmethod.py +34 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_fifo.py +4 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_lfu.py +28 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_lru.py +4 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_rr.py +15 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_tlru.py +70 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_ttl.py +69 -0
- cachetools-8.0.0/AGENTS.md +0 -99
- {cachetools-8.0.0 → cachetools-8.0.2}/LICENSE +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/README.rst +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/docs/conf.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/pyproject.toml +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/setup.cfg +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/func.pyi +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/keys.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/keys.pyi +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools/py.typed +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools.egg-info/dependency_links.txt +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/src/cachetools.egg-info/top_level.txt +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_cache.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_func.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_keys.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tests/test_threading.py +0 -0
- {cachetools-8.0.0 → cachetools-8.0.2}/tox.ini +0 -0
|
@@ -1,3 +1,35 @@
|
|
|
1
|
+
v8.0.2 (2026-11-18)
|
|
2
|
+
===================
|
|
3
|
+
|
|
4
|
+
- Fix deep-copying ``TTLCache`` and ``TLRUCache`` instances whose
|
|
5
|
+
timer defines ``__deepcopy__``.
|
|
6
|
+
|
|
7
|
+
- Fix updating ``TTLCache`` and ``TLRUCache`` items while iterating,
|
|
8
|
+
which skipped or repeated keys.
|
|
9
|
+
|
|
10
|
+
- Minor code improvements.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
v8.0.1 (2026-11-17)
|
|
14
|
+
===================
|
|
15
|
+
|
|
16
|
+
- Fix copying and deep-copying ``@cached`` wrappers of callables
|
|
17
|
+
without a ``__qualname__``, e.g. ``functools.partial`` objects
|
|
18
|
+
(broken since v8.0.0).
|
|
19
|
+
|
|
20
|
+
- Fix deep-copying and pickling ``LFUCache`` instances with many
|
|
21
|
+
different use counts (broken since v6.1.0).
|
|
22
|
+
|
|
23
|
+
- Properly support shallow copies of caches, including subclasses
|
|
24
|
+
with additional attributes.
|
|
25
|
+
|
|
26
|
+
- Minor ``LRUCache`` performance improvements.
|
|
27
|
+
|
|
28
|
+
- Minor ``@cachedmethod`` error handling improvements.
|
|
29
|
+
|
|
30
|
+
- Minor documentation improvements.
|
|
31
|
+
|
|
32
|
+
|
|
1
33
|
v8.0.0 (2026-11-06)
|
|
2
34
|
===================
|
|
3
35
|
|
|
@@ -31,6 +63,25 @@ v8.0.0 (2026-11-06)
|
|
|
31
63
|
- Various test improvements.
|
|
32
64
|
|
|
33
65
|
|
|
66
|
+
v7.3.2 (2026-11-14)
|
|
67
|
+
===================
|
|
68
|
+
|
|
69
|
+
- Properly support shallow copies of caches, including subclasses
|
|
70
|
+
with additional attributes (broken since v7.3.1).
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
v7.3.1 (2026-11-12)
|
|
74
|
+
===================
|
|
75
|
+
|
|
76
|
+
- Fix deep-copying and pickling ``LFUCache`` instances with many
|
|
77
|
+
different use counts (broken since v6.1.0).
|
|
78
|
+
|
|
79
|
+
- Fix shallow copies of caches sharing internal state with the
|
|
80
|
+
original.
|
|
81
|
+
|
|
82
|
+
- Minor documentation improvements.
|
|
83
|
+
|
|
84
|
+
|
|
34
85
|
v7.3.0 (2026-11-05)
|
|
35
86
|
===================
|
|
36
87
|
|
|
@@ -651,6 +651,16 @@ often called with the same arguments:
|
|
|
651
651
|
restores its methods with fresh :meth:`cache_info()` statistics,
|
|
652
652
|
i.e. with the hit and miss counts reset to zero.
|
|
653
653
|
|
|
654
|
+
.. note::
|
|
655
|
+
|
|
656
|
+
Once a decorated method has been accessed on an instance, a
|
|
657
|
+
*shallow* copy of that instance, e.g. one made with
|
|
658
|
+
:func:`copy.copy`, shares the method with the original, and it
|
|
659
|
+
stays bound to the instance that accessed it first. To avoid
|
|
660
|
+
this, make shallow copies before any decorated method is
|
|
661
|
+
accessed, use :func:`copy.deepcopy`, or define a
|
|
662
|
+
:meth:`__copy__` method that creates the copy from scratch.
|
|
663
|
+
|
|
654
664
|
When using a shared cache for multiple methods, be aware that
|
|
655
665
|
different cache keys must be created for each method even when
|
|
656
666
|
function arguments are the same, just as with the :func:`cached`
|
|
@@ -13,7 +13,7 @@ __all__ = (
|
|
|
13
13
|
"cachedmethod",
|
|
14
14
|
)
|
|
15
15
|
|
|
16
|
-
__version__ = "8.0.
|
|
16
|
+
__version__ = "8.0.2"
|
|
17
17
|
|
|
18
18
|
import collections
|
|
19
19
|
import collections.abc
|
|
@@ -113,8 +113,21 @@ class Cache(collections.abc.MutableMapping):
|
|
|
113
113
|
def __len__(self):
|
|
114
114
|
return len(self.__data)
|
|
115
115
|
|
|
116
|
+
# Instance attributes are shared with the copy, except for the
|
|
117
|
+
# cache's own data. Subclasses providing additional attributes
|
|
118
|
+
# that must not be shared should implement their own __copy__.
|
|
119
|
+
|
|
120
|
+
def __copy__(self):
|
|
121
|
+
cls = type(self)
|
|
122
|
+
copy = cls.__new__(cls)
|
|
123
|
+
copy.__dict__.update(self.__dict__)
|
|
124
|
+
copy.__data = self.__data.copy()
|
|
125
|
+
if self.__size is not None:
|
|
126
|
+
copy.__size = self.__size.copy()
|
|
127
|
+
return copy
|
|
128
|
+
|
|
116
129
|
# Note that we cannot simply inherit get(), pop() and setdefault()
|
|
117
|
-
# from MutableMapping, since these rely on __getitem__
|
|
130
|
+
# from MutableMapping, since these rely on __getitem__ raising a
|
|
118
131
|
# KeyError on cache miss. This is not the case if __missing__ is
|
|
119
132
|
# implemented for a Cache subclass, so we have to roll our own,
|
|
120
133
|
# somewhat less elegant versions.
|
|
@@ -189,6 +202,11 @@ class FIFOCache(Cache):
|
|
|
189
202
|
cache_delitem(self, key)
|
|
190
203
|
del self.__order[key]
|
|
191
204
|
|
|
205
|
+
def __copy__(self):
|
|
206
|
+
copy = super().__copy__()
|
|
207
|
+
copy.__order = self.__order.copy()
|
|
208
|
+
return copy
|
|
209
|
+
|
|
192
210
|
def popitem(self):
|
|
193
211
|
"""Remove and return the `(key, value)` pair first inserted."""
|
|
194
212
|
try:
|
|
@@ -215,6 +233,14 @@ class LFUCache(Cache):
|
|
|
215
233
|
self.count = count
|
|
216
234
|
self.keys = collections.OrderedDict()
|
|
217
235
|
|
|
236
|
+
def __reduce__(self):
|
|
237
|
+
return LFUCache._Link, (self.count,), (None, {"keys": self.keys})
|
|
238
|
+
|
|
239
|
+
def insert(self, next):
|
|
240
|
+
self.next = next
|
|
241
|
+
self.prev = prev = next.prev
|
|
242
|
+
prev.next = next.prev = self
|
|
243
|
+
|
|
218
244
|
def unlink(self):
|
|
219
245
|
next = self.next
|
|
220
246
|
prev = self.prev
|
|
@@ -229,7 +255,7 @@ class LFUCache(Cache):
|
|
|
229
255
|
|
|
230
256
|
def __getitem__(self, key, cache_getitem=Cache.__getitem__):
|
|
231
257
|
value = cache_getitem(self, key)
|
|
232
|
-
if key in self.__links: # __missing__ may not store item
|
|
258
|
+
if key in self.__links: # __missing__ may not store the item
|
|
233
259
|
self.__touch(key)
|
|
234
260
|
return value
|
|
235
261
|
|
|
@@ -255,13 +281,35 @@ class LFUCache(Cache):
|
|
|
255
281
|
if not link.keys:
|
|
256
282
|
link.unlink()
|
|
257
283
|
|
|
284
|
+
def __copy__(self):
|
|
285
|
+
copy = super().__copy__()
|
|
286
|
+
copy.__root = root = LFUCache._Link(0)
|
|
287
|
+
root.prev = root.next = root
|
|
288
|
+
copy.__links = links = {}
|
|
289
|
+
curr = self.__root.next
|
|
290
|
+
while curr is not self.__root:
|
|
291
|
+
link = LFUCache._Link(curr.count)
|
|
292
|
+
link.keys = curr.keys.copy()
|
|
293
|
+
link.insert(root)
|
|
294
|
+
links.update(dict.fromkeys(link.keys, link))
|
|
295
|
+
curr = curr.next
|
|
296
|
+
return copy
|
|
297
|
+
|
|
298
|
+
def __setstate__(self, state):
|
|
299
|
+
self.__dict__.update(state)
|
|
300
|
+
root = self.__root
|
|
301
|
+
root.prev = root.next = root
|
|
302
|
+
links = set(self.__links.values())
|
|
303
|
+
for link in sorted(links, key=lambda obj: obj.count):
|
|
304
|
+
link.insert(root)
|
|
305
|
+
|
|
258
306
|
def popitem(self):
|
|
259
307
|
"""Remove and return the `(key, value)` pair least frequently used."""
|
|
260
308
|
root = self.__root
|
|
261
309
|
curr = root.next
|
|
262
310
|
if curr is root:
|
|
263
311
|
raise KeyError("%s is empty" % type(self).__name__) from None
|
|
264
|
-
key = next(iter(curr.keys)) #
|
|
312
|
+
key = next(iter(curr.keys)) # least recently used key with the lowest use count
|
|
265
313
|
value = Cache.__getitem__(self, key)
|
|
266
314
|
del self[key]
|
|
267
315
|
return (key, value)
|
|
@@ -302,18 +350,27 @@ class LRUCache(Cache):
|
|
|
302
350
|
value = cache_getitem(self, key)
|
|
303
351
|
try:
|
|
304
352
|
self.__order.move_to_end(key)
|
|
305
|
-
except KeyError: # __missing__ may not store item
|
|
353
|
+
except KeyError: # __missing__ may not store the item
|
|
306
354
|
pass
|
|
307
355
|
return value
|
|
308
356
|
|
|
309
357
|
def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
|
|
310
358
|
cache_setitem(self, key, value)
|
|
311
|
-
self.
|
|
359
|
+
order = self.__order
|
|
360
|
+
if key in order:
|
|
361
|
+
order.move_to_end(key)
|
|
362
|
+
else:
|
|
363
|
+
order[key] = None
|
|
312
364
|
|
|
313
365
|
def __delitem__(self, key, cache_delitem=Cache.__delitem__):
|
|
314
366
|
cache_delitem(self, key)
|
|
315
367
|
del self.__order[key]
|
|
316
368
|
|
|
369
|
+
def __copy__(self):
|
|
370
|
+
copy = super().__copy__()
|
|
371
|
+
copy.__order = self.__order.copy()
|
|
372
|
+
return copy
|
|
373
|
+
|
|
317
374
|
def popitem(self):
|
|
318
375
|
"""Remove and return the `(key, value)` pair least recently used."""
|
|
319
376
|
try:
|
|
@@ -329,13 +386,6 @@ class LRUCache(Cache):
|
|
|
329
386
|
Cache.clear(self)
|
|
330
387
|
self.__order.clear()
|
|
331
388
|
|
|
332
|
-
def __touch(self, key):
|
|
333
|
-
"""Mark as recently used."""
|
|
334
|
-
try:
|
|
335
|
-
self.__order.move_to_end(key)
|
|
336
|
-
except KeyError:
|
|
337
|
-
self.__order[key] = None
|
|
338
|
-
|
|
339
389
|
|
|
340
390
|
class RRCache(Cache):
|
|
341
391
|
"""Random Replacement (RR) cache implementation."""
|
|
@@ -346,6 +396,12 @@ class RRCache(Cache):
|
|
|
346
396
|
self.__index = {}
|
|
347
397
|
self.__keys = []
|
|
348
398
|
|
|
399
|
+
def __copy__(self):
|
|
400
|
+
copy = super().__copy__()
|
|
401
|
+
copy.__index = self.__index.copy()
|
|
402
|
+
copy.__keys = self.__keys.copy()
|
|
403
|
+
return copy
|
|
404
|
+
|
|
349
405
|
@property
|
|
350
406
|
def choice(self):
|
|
351
407
|
"""The `choice` function used by the cache."""
|
|
@@ -407,6 +463,15 @@ class _TimedCache(Cache):
|
|
|
407
463
|
def __exit__(self, *exc):
|
|
408
464
|
self.__nesting -= 1
|
|
409
465
|
|
|
466
|
+
def __copy__(self):
|
|
467
|
+
return _TimedCache._Timer(self.__timer)
|
|
468
|
+
|
|
469
|
+
def __deepcopy__(self, memo):
|
|
470
|
+
# otherwise __getattr__ forwards to the timer's own __deepcopy__
|
|
471
|
+
import copy
|
|
472
|
+
|
|
473
|
+
return _TimedCache._Timer(copy.deepcopy(self.__timer, memo))
|
|
474
|
+
|
|
410
475
|
def __reduce__(self):
|
|
411
476
|
return _TimedCache._Timer, (self.__timer,)
|
|
412
477
|
|
|
@@ -417,6 +482,11 @@ class _TimedCache(Cache):
|
|
|
417
482
|
Cache.__init__(self, maxsize, getsizeof)
|
|
418
483
|
self.__timer = _TimedCache._Timer(timer)
|
|
419
484
|
|
|
485
|
+
def __copy__(self):
|
|
486
|
+
copy = super().__copy__()
|
|
487
|
+
copy.__timer = self.__timer.__copy__()
|
|
488
|
+
return copy
|
|
489
|
+
|
|
420
490
|
def __repr__(self, cache_repr=Cache.__repr__):
|
|
421
491
|
with self.__timer as time:
|
|
422
492
|
self.expire(time)
|
|
@@ -451,9 +521,9 @@ class _TimedCache(Cache):
|
|
|
451
521
|
return Cache.setdefault(self, *args, **kwargs)
|
|
452
522
|
|
|
453
523
|
def clear(self):
|
|
454
|
-
# Subclasses must override to also reset their own
|
|
455
|
-
# structures
|
|
456
|
-
# be O(1) regardless of cache contents.
|
|
524
|
+
# Subclasses must override this to also reset their own
|
|
525
|
+
# time-tracking structures. We do not call expire() here,
|
|
526
|
+
# since clear() should be O(1) regardless of cache contents.
|
|
457
527
|
Cache.clear(self)
|
|
458
528
|
|
|
459
529
|
def expire(self, time=None): # pragma: no cover
|
|
@@ -473,6 +543,11 @@ class TTLCache(_TimedCache):
|
|
|
473
543
|
def __reduce__(self):
|
|
474
544
|
return TTLCache._Link, (self.key, self.expires)
|
|
475
545
|
|
|
546
|
+
def insert(self, next):
|
|
547
|
+
self.next = next
|
|
548
|
+
self.prev = prev = next.prev
|
|
549
|
+
prev.next = next.prev = self
|
|
550
|
+
|
|
476
551
|
def unlink(self):
|
|
477
552
|
next = self.next
|
|
478
553
|
prev = self.prev
|
|
@@ -519,9 +594,7 @@ class TTLCache(_TimedCache):
|
|
|
519
594
|
links.move_to_end(key)
|
|
520
595
|
link.unlink()
|
|
521
596
|
link.expires = expires
|
|
522
|
-
link.
|
|
523
|
-
link.prev = prev = root.prev
|
|
524
|
-
prev.next = root.prev = link
|
|
597
|
+
link.insert(self.__root)
|
|
525
598
|
|
|
526
599
|
def __delitem__(self, key, cache_delitem=Cache.__delitem__):
|
|
527
600
|
cache_delitem(self, key)
|
|
@@ -531,23 +604,37 @@ class TTLCache(_TimedCache):
|
|
|
531
604
|
raise KeyError(key)
|
|
532
605
|
|
|
533
606
|
def __iter__(self):
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
607
|
+
# Iterate over a snapshot of keys, in insertion order. Inserting or
|
|
608
|
+
# deleting items while iterating does not raise RuntimeError as for
|
|
609
|
+
# dict, since items may also expire meanwhile.
|
|
610
|
+
for key in list(Cache.__iter__(self)):
|
|
537
611
|
# "freeze" time for iterator access
|
|
538
612
|
with self.timer as time:
|
|
539
|
-
|
|
540
|
-
|
|
613
|
+
link = self.__links.get(key)
|
|
614
|
+
if link is not None and time < link.expires:
|
|
615
|
+
yield key
|
|
616
|
+
|
|
617
|
+
def __copy__(self):
|
|
618
|
+
copy = super().__copy__()
|
|
619
|
+
copy.__root = root = TTLCache._Link()
|
|
620
|
+
root.prev = root.next = root
|
|
621
|
+
links = {}
|
|
622
|
+
curr = self.__root.next
|
|
623
|
+
while curr is not self.__root:
|
|
624
|
+
links[curr.key] = link = TTLCache._Link(curr.key, curr.expires)
|
|
625
|
+
link.insert(root)
|
|
541
626
|
curr = curr.next
|
|
627
|
+
copy.__links = collections.OrderedDict(
|
|
628
|
+
(key, links[key]) for key in self.__links
|
|
629
|
+
)
|
|
630
|
+
return copy
|
|
542
631
|
|
|
543
632
|
def __setstate__(self, state):
|
|
544
633
|
self.__dict__.update(state)
|
|
545
634
|
root = self.__root
|
|
546
635
|
root.prev = root.next = root
|
|
547
636
|
for link in sorted(self.__links.values(), key=lambda obj: obj.expires):
|
|
548
|
-
link.
|
|
549
|
-
link.prev = prev = root.prev
|
|
550
|
-
prev.next = root.prev = link
|
|
637
|
+
link.insert(root)
|
|
551
638
|
self.expire(self.timer())
|
|
552
639
|
|
|
553
640
|
@property
|
|
@@ -650,12 +737,12 @@ class TLRUCache(_TimedCache):
|
|
|
650
737
|
self.expire(time)
|
|
651
738
|
expires = self.__ttu(key, value, time)
|
|
652
739
|
if not (time < expires):
|
|
653
|
-
#
|
|
654
|
-
# one should remove the existing item
|
|
740
|
+
# Updating an existing item with an already expired
|
|
741
|
+
# one should remove the existing item.
|
|
655
742
|
return self.__delitem(key)
|
|
656
743
|
cache_setitem(self, key, value)
|
|
657
|
-
#
|
|
658
|
-
# only mark it as removed for now
|
|
744
|
+
# Removing an existing item would break the heap structure, so
|
|
745
|
+
# only mark it as removed for now.
|
|
659
746
|
items = self.__items
|
|
660
747
|
item = items.get(key)
|
|
661
748
|
if item is not None:
|
|
@@ -666,7 +753,7 @@ class TLRUCache(_TimedCache):
|
|
|
666
753
|
|
|
667
754
|
def __delitem__(self, key, cache_delitem=Cache.__delitem__):
|
|
668
755
|
with self.timer as time:
|
|
669
|
-
# no self.expire() for performance reasons, e.g.
|
|
756
|
+
# no self.expire() for performance reasons, e.g. when evicting [#67]
|
|
670
757
|
cache_delitem(self, key)
|
|
671
758
|
item = self.__items.pop(key)
|
|
672
759
|
item.removed = True
|
|
@@ -674,11 +761,27 @@ class TLRUCache(_TimedCache):
|
|
|
674
761
|
raise KeyError(key)
|
|
675
762
|
|
|
676
763
|
def __iter__(self):
|
|
677
|
-
|
|
764
|
+
# Iterate over a snapshot of keys, in insertion order. Inserting or
|
|
765
|
+
# deleting items while iterating does not raise RuntimeError as for
|
|
766
|
+
# dict, since items may also expire meanwhile.
|
|
767
|
+
for key in list(Cache.__iter__(self)):
|
|
678
768
|
# "freeze" time for iterator access
|
|
679
769
|
with self.timer as time:
|
|
680
|
-
|
|
681
|
-
|
|
770
|
+
item = self.__items.get(key)
|
|
771
|
+
if item is not None and time < item.expires:
|
|
772
|
+
yield key
|
|
773
|
+
|
|
774
|
+
def __copy__(self):
|
|
775
|
+
copy = super().__copy__()
|
|
776
|
+
items = {}
|
|
777
|
+
for item in self.__order:
|
|
778
|
+
items[item] = new = TLRUCache._Item(item.key, item.expires)
|
|
779
|
+
new.removed = item.removed
|
|
780
|
+
copy.__order = [items[item] for item in self.__order]
|
|
781
|
+
copy.__items = collections.OrderedDict(
|
|
782
|
+
(key, items[item]) for key, item in self.__items.items()
|
|
783
|
+
)
|
|
784
|
+
return copy
|
|
682
785
|
|
|
683
786
|
@property
|
|
684
787
|
def ttu(self):
|
|
@@ -761,7 +864,7 @@ def cached(cache, key=keys.hashkey, lock=None, condition=None, info=False):
|
|
|
761
864
|
"""
|
|
762
865
|
from ._cached import _wrapper
|
|
763
866
|
|
|
764
|
-
if cache is None: #
|
|
867
|
+
if cache is None: # unsupported since v8.0.0
|
|
765
868
|
raise TypeError("cache must not be None")
|
|
766
869
|
|
|
767
870
|
def decorator(func):
|
|
@@ -778,6 +881,9 @@ def cachedmethod(cache, key=keys.methodkey, lock=None, condition=None, info=Fals
|
|
|
778
881
|
"""
|
|
779
882
|
from ._cachedmethod import _wrapper
|
|
780
883
|
|
|
884
|
+
if not callable(cache):
|
|
885
|
+
raise TypeError("cache must be callable")
|
|
886
|
+
|
|
781
887
|
def decorator(method):
|
|
782
888
|
make_info = CacheInfo._make_info if info else None
|
|
783
889
|
return _wrapper(method, cache, key, lock, condition, make_info)
|
|
@@ -193,8 +193,8 @@ class _cached_wrapper_info(_cached_wrapper[_P, _R]):
|
|
|
193
193
|
obj: _S,
|
|
194
194
|
objtype: type | None = None,
|
|
195
195
|
) -> _cached_wrapper_info[_Q, _R]: ...
|
|
196
|
-
#
|
|
197
|
-
# the _cached_wrapper_info subtype of the corresponding base return type
|
|
196
|
+
# Pyright cannot match the self-typed base overload. Each return type is
|
|
197
|
+
# the _cached_wrapper_info subtype of the corresponding base return type.
|
|
198
198
|
@overload
|
|
199
199
|
def __get__( # pyright: ignore[reportIncompatibleMethodOverride]
|
|
200
200
|
self, obj: object, objtype: type | None = None
|
|
@@ -27,18 +27,24 @@ class _WrapperBase:
|
|
|
27
27
|
"""Wrapper base class providing the public cache attributes."""
|
|
28
28
|
|
|
29
29
|
def __init__(self, func, cache, key, lock=None, cond=None):
|
|
30
|
-
#
|
|
31
|
-
# e.g. when stacking decorators
|
|
30
|
+
# Update first, so func.__dict__ cannot override wrapper state,
|
|
31
|
+
# e.g. when stacking decorators.
|
|
32
32
|
functools.update_wrapper(self, func)
|
|
33
33
|
self.cache = cache
|
|
34
34
|
self.cache_key = key
|
|
35
35
|
self.cache_lock = lock
|
|
36
36
|
self.cache_condition = cond
|
|
37
37
|
|
|
38
|
-
# descriptor and pickle support as for functools.lru_cache (C version)
|
|
38
|
+
# descriptor, copy and pickle support as for functools.lru_cache (C version)
|
|
39
39
|
def __get__(self, obj, objtype=None):
|
|
40
40
|
return self if obj is None else types.MethodType(self, obj)
|
|
41
41
|
|
|
42
|
+
def __copy__(self):
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def __deepcopy__(self, memo):
|
|
46
|
+
return self
|
|
47
|
+
|
|
42
48
|
def __reduce__(self):
|
|
43
49
|
return self.__qualname__
|
|
44
50
|
|
|
@@ -37,10 +37,10 @@ class _WrapperBase:
|
|
|
37
37
|
self.cache_key = functools.partial(key, obj)
|
|
38
38
|
|
|
39
39
|
def __reduce__(self):
|
|
40
|
-
#
|
|
41
|
-
# internals, e.g. __wrapped__, lock/cond closures
|
|
42
|
-
# this will also reset
|
|
43
|
-
# wrappers
|
|
40
|
+
# Rebuild via the descriptor instead of pickling unpicklable
|
|
41
|
+
# internals, e.g. __wrapped__, lock/cond closures. Note that
|
|
42
|
+
# this will also reset the hit and miss counts of *Info*
|
|
43
|
+
# wrappers.
|
|
44
44
|
return (self.__descriptor.__get__, (self.__obj,))
|
|
45
45
|
|
|
46
46
|
def __repr__(self):
|
|
@@ -75,7 +75,6 @@ class _ConditionMixin:
|
|
|
75
75
|
cond = self.cache_condition
|
|
76
76
|
|
|
77
77
|
with lock:
|
|
78
|
-
# apparently significantly faster than cond.wait_for(...)
|
|
79
78
|
while key in self.__pending:
|
|
80
79
|
cond.wait()
|
|
81
80
|
try:
|
|
@@ -183,7 +182,6 @@ class _ConditionInfoMixin:
|
|
|
183
182
|
cond = self.cache_condition
|
|
184
183
|
|
|
185
184
|
with lock:
|
|
186
|
-
# apparently significantly faster than cond.wait_for(...)
|
|
187
185
|
while key in self.__pending:
|
|
188
186
|
cond.wait()
|
|
189
187
|
try:
|
|
@@ -31,8 +31,8 @@ class _MethodDescriptor:
|
|
|
31
31
|
|
|
32
32
|
if attrname is None:
|
|
33
33
|
if isinstance(obj, type):
|
|
34
|
-
#
|
|
35
|
-
# without forwarding __set_name__
|
|
34
|
+
# Before Python 3.13, @classmethod calls __get__(cls, type(cls))
|
|
35
|
+
# without forwarding __set_name__.
|
|
36
36
|
self.__call__() # raise TypeError as in Python >= 3.13
|
|
37
37
|
msg = "Cannot use descriptor instance without calling __set_name__ on it"
|
|
38
38
|
raise TypeError(msg) from None
|
|
@@ -48,9 +48,9 @@ class _MethodDescriptor:
|
|
|
48
48
|
else:
|
|
49
49
|
descriptor = None # removed from the class after __set_name__
|
|
50
50
|
if descriptor is self:
|
|
51
|
-
#
|
|
52
|
-
# of a race condition where another thread already
|
|
53
|
-
# descriptor, prefer the initial wrapper.
|
|
51
|
+
# Replace the descriptor instance with the wrapper in the instance
|
|
52
|
+
# dict. In case of a race condition where another thread already
|
|
53
|
+
# replaced the descriptor, prefer the initial wrapper.
|
|
54
54
|
wrapper = self.__wrapper(obj, self)
|
|
55
55
|
try:
|
|
56
56
|
wrapper = obj.__dict__.setdefault(attrname, wrapper)
|
|
@@ -70,17 +70,22 @@ class _MethodDescriptor:
|
|
|
70
70
|
return wrapper
|
|
71
71
|
|
|
72
72
|
def __reduce__(self):
|
|
73
|
-
#
|
|
74
|
-
# "__cachetools_cachedmethods" can be pickled and deep-copied
|
|
73
|
+
# Pickle and copy by reference, so wrappers and their keys in
|
|
74
|
+
# "__cachetools_cachedmethods" can be pickled and deep-copied.
|
|
75
75
|
return (self._lookup, (self.__owner, self.__attrname))
|
|
76
76
|
|
|
77
77
|
@staticmethod
|
|
78
78
|
def _lookup(owner, name):
|
|
79
79
|
return owner.__dict__[name]
|
|
80
80
|
|
|
81
|
-
#
|
|
81
|
+
# Called by whatever wraps the descriptor: @classmethod since Python
|
|
82
|
+
# 3.13, @staticmethod, @property or any other function decorator.
|
|
82
83
|
def __call__(self, /, *args, **kwargs):
|
|
83
|
-
raise TypeError(
|
|
84
|
+
raise TypeError(
|
|
85
|
+
"Cannot call @cachedmethod descriptor directly: @cachedmethod must "
|
|
86
|
+
"be the outermost decorator, and decorating class methods, static "
|
|
87
|
+
"methods or properties is not supported"
|
|
88
|
+
)
|
|
84
89
|
|
|
85
90
|
def __get_unbound(self):
|
|
86
91
|
# created once and shared by all class accesses
|
|
@@ -90,7 +95,7 @@ class _MethodDescriptor:
|
|
|
90
95
|
|
|
91
96
|
def __instance_dict_error(self, obj, error):
|
|
92
97
|
if isinstance(error, AttributeError):
|
|
93
|
-
# not all objects have __dict__ (e.g. class defines
|
|
98
|
+
# not all objects have __dict__ (e.g. if the class defines __slots__)
|
|
94
99
|
msg = (
|
|
95
100
|
f"No '__dict__' attribute on {type(obj).__name__!r} "
|
|
96
101
|
f"instance to cache {self.__attrname!r}"
|
|
@@ -132,8 +137,8 @@ class _Unbound:
|
|
|
132
137
|
return self
|
|
133
138
|
return self.__descriptor.__get__(obj)
|
|
134
139
|
|
|
135
|
-
#
|
|
136
|
-
# as they did before class access returned a callable.
|
|
140
|
+
# The receiver is taken from *args, so autospec'd instances accept any
|
|
141
|
+
# call, as they did before class access returned a callable.
|
|
137
142
|
def __call__(self, /, *args, **kwargs):
|
|
138
143
|
if args:
|
|
139
144
|
obj, *args = args
|
|
@@ -21,9 +21,8 @@ class _UnboundTTLCache(TTLCache):
|
|
|
21
21
|
|
|
22
22
|
def _cache(cache, maxsize, typed):
|
|
23
23
|
def decorator(func):
|
|
24
|
-
#
|
|
25
|
-
#
|
|
26
|
-
# using a condition variable
|
|
24
|
+
# Like functools.lru_cache, this has to be thread-safe. Using
|
|
25
|
+
# a condition variable also prevents cache stampedes.
|
|
27
26
|
key = keys.typedkey if typed else keys.hashkey
|
|
28
27
|
wrapper = cached(cache=cache, key=key, condition=Condition(), info=True)(func)
|
|
29
28
|
wrapper.cache_parameters = lambda: {"maxsize": maxsize, "typed": typed} # type: ignore
|
|
@@ -457,6 +457,18 @@ class CacheTestMixin(SimplifiedTestCaseProtocol):
|
|
|
457
457
|
self.assertEqual(1, len(cache))
|
|
458
458
|
self.assertEqual(4, cache.currsize)
|
|
459
459
|
|
|
460
|
+
def test_iter_update(self):
|
|
461
|
+
cache = self.Cache(maxsize=3)
|
|
462
|
+
cache.update({1: 1, 2: 2, 3: 3})
|
|
463
|
+
|
|
464
|
+
# updating items while iterating visits each key once, in order
|
|
465
|
+
keys = []
|
|
466
|
+
for key in cache:
|
|
467
|
+
keys.append(key)
|
|
468
|
+
cache[key] = key * 10
|
|
469
|
+
self.assertEqual([1, 2, 3], keys)
|
|
470
|
+
self.assertEqual([10, 20, 30], list(cache.values()))
|
|
471
|
+
|
|
460
472
|
def test_pickle(self):
|
|
461
473
|
import pickle
|
|
462
474
|
|
|
@@ -464,7 +476,10 @@ class CacheTestMixin(SimplifiedTestCaseProtocol):
|
|
|
464
476
|
source.update({1: 1, 2: 2})
|
|
465
477
|
|
|
466
478
|
cache = pickle.loads(pickle.dumps(source))
|
|
479
|
+
self.assertIsNot(source, cache)
|
|
467
480
|
self.assertEqual(source, cache)
|
|
481
|
+
self.assertEqual(source.maxsize, cache.maxsize)
|
|
482
|
+
self.assertEqual(source.currsize, cache.currsize)
|
|
468
483
|
|
|
469
484
|
self.assertEqual(2, len(cache))
|
|
470
485
|
self.assertEqual(1, cache[1])
|
|
@@ -472,13 +487,15 @@ class CacheTestMixin(SimplifiedTestCaseProtocol):
|
|
|
472
487
|
|
|
473
488
|
cache[3] = 3
|
|
474
489
|
self.assertEqual(2, len(cache))
|
|
490
|
+
self.assertEqual(2, cache.currsize)
|
|
475
491
|
self.assertEqual(3, cache[3])
|
|
476
492
|
self.assertTrue(1 in cache or 2 in cache)
|
|
477
493
|
|
|
478
|
-
|
|
479
|
-
self.assertEqual(2,
|
|
480
|
-
self.
|
|
481
|
-
self.
|
|
494
|
+
self.assertEqual(2, len(source))
|
|
495
|
+
self.assertEqual(2, source.currsize)
|
|
496
|
+
self.assertIn(1, source)
|
|
497
|
+
self.assertIn(2, source)
|
|
498
|
+
self.assertNotIn(3, source)
|
|
482
499
|
|
|
483
500
|
self.assertEqual(cache, pickle.loads(pickle.dumps(cache)))
|
|
484
501
|
|
|
@@ -493,3 +510,142 @@ class CacheTestMixin(SimplifiedTestCaseProtocol):
|
|
|
493
510
|
cache = pickle.loads(pickle.dumps(source))
|
|
494
511
|
self.assertEqual(n, len(cache))
|
|
495
512
|
self.assertEqual(source, cache)
|
|
513
|
+
|
|
514
|
+
def test_copy(self):
|
|
515
|
+
import copy
|
|
516
|
+
|
|
517
|
+
source = self.Cache(maxsize=2)
|
|
518
|
+
source.update({1: 1, 2: 2})
|
|
519
|
+
|
|
520
|
+
cache = copy.copy(source)
|
|
521
|
+
self.assertIsNot(source, cache)
|
|
522
|
+
self.assertEqual(source, cache)
|
|
523
|
+
self.assertEqual(source.maxsize, cache.maxsize)
|
|
524
|
+
self.assertEqual(source.currsize, cache.currsize)
|
|
525
|
+
|
|
526
|
+
self.assertEqual(2, len(cache))
|
|
527
|
+
self.assertEqual(1, cache[1])
|
|
528
|
+
self.assertEqual(2, cache[2])
|
|
529
|
+
|
|
530
|
+
cache[3] = 3
|
|
531
|
+
self.assertEqual(2, len(cache))
|
|
532
|
+
self.assertEqual(2, cache.currsize)
|
|
533
|
+
self.assertEqual(3, cache[3])
|
|
534
|
+
self.assertTrue(1 in cache or 2 in cache)
|
|
535
|
+
|
|
536
|
+
self.assertEqual(2, len(source))
|
|
537
|
+
self.assertEqual(2, source.currsize)
|
|
538
|
+
self.assertIn(1, source)
|
|
539
|
+
self.assertIn(2, source)
|
|
540
|
+
self.assertNotIn(3, source)
|
|
541
|
+
|
|
542
|
+
self.assertEqual(cache, copy.copy(cache))
|
|
543
|
+
|
|
544
|
+
def test_copy_maxsize(self):
|
|
545
|
+
import copy
|
|
546
|
+
import sys
|
|
547
|
+
|
|
548
|
+
# test empty cache, single element, large cache (recursion limit)
|
|
549
|
+
for n in [0, 1, sys.getrecursionlimit() * 2]:
|
|
550
|
+
source = self.Cache(maxsize=n)
|
|
551
|
+
source.update((i, i) for i in range(n))
|
|
552
|
+
cache = copy.copy(source)
|
|
553
|
+
self.assertEqual(n, len(cache))
|
|
554
|
+
self.assertEqual(source, cache)
|
|
555
|
+
|
|
556
|
+
def test_copy_attributes(self):
|
|
557
|
+
import copy
|
|
558
|
+
import threading
|
|
559
|
+
|
|
560
|
+
class Cache(self.Cache):
|
|
561
|
+
def __init__(self, maxsize, **kwargs):
|
|
562
|
+
super().__init__(maxsize, **kwargs)
|
|
563
|
+
self.lock = threading.Lock() # cannot be deep-copied
|
|
564
|
+
self.stats = {"hits": 0}
|
|
565
|
+
|
|
566
|
+
source = Cache(maxsize=2)
|
|
567
|
+
source.update({1: [1], 2: [2]})
|
|
568
|
+
|
|
569
|
+
cache = copy.copy(source)
|
|
570
|
+
self.assertIs(type(source), type(cache))
|
|
571
|
+
# a shallow copy shares attributes and values with its source
|
|
572
|
+
self.assertIs(source.lock, cache.lock)
|
|
573
|
+
self.assertIs(source.stats, cache.stats)
|
|
574
|
+
self.assertIs(source[1], cache[1])
|
|
575
|
+
self.assertIs(source[2], cache[2])
|
|
576
|
+
|
|
577
|
+
# but none of the cache's own state
|
|
578
|
+
cache[3] = [3]
|
|
579
|
+
del cache[next(iter(cache))]
|
|
580
|
+
self.assertEqual(1, len(cache))
|
|
581
|
+
self.assertEqual(2, len(source))
|
|
582
|
+
self.assertEqual(2, source.currsize)
|
|
583
|
+
self.assertIn(1, source)
|
|
584
|
+
self.assertIn(2, source)
|
|
585
|
+
self.assertNotIn(3, source)
|
|
586
|
+
|
|
587
|
+
def test_copy_getsizeof(self):
|
|
588
|
+
import copy
|
|
589
|
+
|
|
590
|
+
class GetSizeOf:
|
|
591
|
+
def __call__(self, value):
|
|
592
|
+
return value
|
|
593
|
+
|
|
594
|
+
source = self.Cache(maxsize=3, getsizeof=GetSizeOf())
|
|
595
|
+
source.update({1: 1, 2: 2})
|
|
596
|
+
|
|
597
|
+
cache = copy.copy(source)
|
|
598
|
+
self.assertIs(source.getsizeof, cache.getsizeof)
|
|
599
|
+
self.assertEqual(3, cache.currsize)
|
|
600
|
+
|
|
601
|
+
# item sizes are kept separately for source and copy
|
|
602
|
+
cache[2] = 1
|
|
603
|
+
self.assertEqual(2, cache.currsize)
|
|
604
|
+
self.assertEqual(3, source.currsize)
|
|
605
|
+
del source[2]
|
|
606
|
+
self.assertEqual(1, source.currsize)
|
|
607
|
+
self.assertEqual(2, cache.currsize)
|
|
608
|
+
del cache[2]
|
|
609
|
+
self.assertEqual(1, cache.currsize)
|
|
610
|
+
|
|
611
|
+
def test_deepcopy(self):
|
|
612
|
+
import copy
|
|
613
|
+
|
|
614
|
+
source = self.Cache(maxsize=2)
|
|
615
|
+
source.update({1: 1, 2: 2})
|
|
616
|
+
|
|
617
|
+
cache = copy.deepcopy(source)
|
|
618
|
+
self.assertIsNot(source, cache)
|
|
619
|
+
self.assertEqual(source, cache)
|
|
620
|
+
self.assertEqual(source.maxsize, cache.maxsize)
|
|
621
|
+
self.assertEqual(source.currsize, cache.currsize)
|
|
622
|
+
|
|
623
|
+
self.assertEqual(2, len(cache))
|
|
624
|
+
self.assertEqual(1, cache[1])
|
|
625
|
+
self.assertEqual(2, cache[2])
|
|
626
|
+
|
|
627
|
+
cache[3] = 3
|
|
628
|
+
self.assertEqual(2, len(cache))
|
|
629
|
+
self.assertEqual(2, cache.currsize)
|
|
630
|
+
self.assertEqual(3, cache[3])
|
|
631
|
+
self.assertTrue(1 in cache or 2 in cache)
|
|
632
|
+
|
|
633
|
+
self.assertEqual(2, len(source))
|
|
634
|
+
self.assertEqual(2, source.currsize)
|
|
635
|
+
self.assertIn(1, source)
|
|
636
|
+
self.assertIn(2, source)
|
|
637
|
+
self.assertNotIn(3, source)
|
|
638
|
+
|
|
639
|
+
self.assertEqual(cache, copy.deepcopy(cache))
|
|
640
|
+
|
|
641
|
+
def test_deepcopy_maxsize(self):
|
|
642
|
+
import copy
|
|
643
|
+
import sys
|
|
644
|
+
|
|
645
|
+
# test empty cache, single element, large cache (recursion limit)
|
|
646
|
+
for n in [0, 1, sys.getrecursionlimit() * 2]:
|
|
647
|
+
source = self.Cache(maxsize=n)
|
|
648
|
+
source.update((i, i) for i in range(n))
|
|
649
|
+
cache = copy.deepcopy(source)
|
|
650
|
+
self.assertEqual(n, len(cache))
|
|
651
|
+
self.assertEqual(source, cache)
|
|
@@ -631,3 +631,15 @@ class PickleTest(unittest.TestCase):
|
|
|
631
631
|
func = self.pickled_func
|
|
632
632
|
self.assertIs(copy.copy(func), func)
|
|
633
633
|
self.assertIs(copy.deepcopy(func), func)
|
|
634
|
+
|
|
635
|
+
def test_copy_partial(self):
|
|
636
|
+
import copy
|
|
637
|
+
import functools
|
|
638
|
+
|
|
639
|
+
# a partial object has no __qualname__ to be copied by reference with
|
|
640
|
+
partial = functools.partial(int, base=2)
|
|
641
|
+
func = cachetools.cached(cachetools.LRUCache(maxsize=2))(partial)
|
|
642
|
+
self.assertFalse(hasattr(func, "__qualname__"))
|
|
643
|
+
self.assertIs(copy.copy(func), func)
|
|
644
|
+
self.assertIs(copy.deepcopy(func), func)
|
|
645
|
+
self.assertEqual(func("101"), 5)
|
|
@@ -1002,6 +1002,13 @@ class WeakRefMethodTest(unittest.TestCase):
|
|
|
1002
1002
|
|
|
1003
1003
|
|
|
1004
1004
|
class NoneMethodTest(unittest.TestCase):
|
|
1005
|
+
def test_decorator(self):
|
|
1006
|
+
for cache in (None, Cache(2)):
|
|
1007
|
+
with self.assertRaisesRegex(TypeError, "callable"):
|
|
1008
|
+
cachedmethod(cache) # type: ignore
|
|
1009
|
+
with self.assertRaisesRegex(TypeError, "callable"):
|
|
1010
|
+
cachedmethod(cache, info=True) # type: ignore
|
|
1011
|
+
|
|
1005
1012
|
def test_none_info(self):
|
|
1006
1013
|
cached = Cached(None)
|
|
1007
1014
|
wrapper = cached.get_info
|
|
@@ -1169,3 +1176,30 @@ class ClassMethodTest(unittest.TestCase):
|
|
|
1169
1176
|
|
|
1170
1177
|
with self.assertRaisesRegex(TypeError, "class method"):
|
|
1171
1178
|
self.Cached.get_class(42) # type: ignore
|
|
1179
|
+
|
|
1180
|
+
def test_outer_decorator(self):
|
|
1181
|
+
import functools
|
|
1182
|
+
|
|
1183
|
+
def decorator(method):
|
|
1184
|
+
@functools.wraps(method)
|
|
1185
|
+
def wrapper(*args, **kwargs):
|
|
1186
|
+
return method(*args, **kwargs)
|
|
1187
|
+
|
|
1188
|
+
return wrapper
|
|
1189
|
+
|
|
1190
|
+
class Decorated(Cached):
|
|
1191
|
+
@decorator
|
|
1192
|
+
@cachedmethod(lambda self: self.cache)
|
|
1193
|
+
def get_inner(self, value):
|
|
1194
|
+
return 42
|
|
1195
|
+
|
|
1196
|
+
@cachedmethod(lambda self: self.cache)
|
|
1197
|
+
@decorator
|
|
1198
|
+
def get_outer(self, value):
|
|
1199
|
+
return 42
|
|
1200
|
+
|
|
1201
|
+
decorated = Decorated({})
|
|
1202
|
+
with self.assertRaisesRegex(TypeError, "outermost decorator"):
|
|
1203
|
+
decorated.get_inner(42)
|
|
1204
|
+
self.assertEqual(decorated.get_outer(42), 42)
|
|
1205
|
+
self.assertEqual(decorated.cache, {(42,): 42})
|
|
@@ -9,6 +9,8 @@ class FIFOCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
9
9
|
Cache = FIFOCache
|
|
10
10
|
|
|
11
11
|
def test_fifo(self):
|
|
12
|
+
import copy
|
|
13
|
+
|
|
12
14
|
cache = FIFOCache[int, int](maxsize=2)
|
|
13
15
|
|
|
14
16
|
cache[1] = 1
|
|
@@ -21,6 +23,8 @@ class FIFOCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
21
23
|
self.assertNotIn(1, cache)
|
|
22
24
|
|
|
23
25
|
cache[2]
|
|
26
|
+
# a shallow copy evicts in the same order, on its own
|
|
27
|
+
self.assertEqual((2, 2), copy.copy(cache).popitem())
|
|
24
28
|
cache[4] = 4
|
|
25
29
|
self.assertEqual(len(cache), 2)
|
|
26
30
|
self.assertEqual(cache[3], 3)
|
|
@@ -137,3 +137,31 @@ class LFUCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
137
137
|
self.assertIn(3, cache)
|
|
138
138
|
self.assertIn(5, cache)
|
|
139
139
|
self.assertNotIn(4, cache)
|
|
140
|
+
|
|
141
|
+
def test_lfu_copy_use_counts(self):
|
|
142
|
+
"""Regression test for recursion errors from copying and
|
|
143
|
+
pickling LFUCache with many use counts."""
|
|
144
|
+
import copy
|
|
145
|
+
import pickle
|
|
146
|
+
import sys
|
|
147
|
+
|
|
148
|
+
n = sys.getrecursionlimit()
|
|
149
|
+
source = LFUCache[int, int](maxsize=n + 1)
|
|
150
|
+
for key in range(n):
|
|
151
|
+
source[key] = key
|
|
152
|
+
for _ in range(key):
|
|
153
|
+
source[key] # key ends up with use count key + 1
|
|
154
|
+
source[n] = n # tied with key 0 at use count 1
|
|
155
|
+
|
|
156
|
+
for cache in (
|
|
157
|
+
copy.copy(source),
|
|
158
|
+
copy.deepcopy(source),
|
|
159
|
+
pickle.loads(pickle.dumps(source)),
|
|
160
|
+
):
|
|
161
|
+
# compare keys only, since items() would count as a use
|
|
162
|
+
self.assertEqual(list(source), list(cache))
|
|
163
|
+
# the copy evicts by use count, then by age
|
|
164
|
+
order = [cache.popitem()[0] for _ in range(len(cache))]
|
|
165
|
+
self.assertEqual([0, n, *range(1, n)], order)
|
|
166
|
+
|
|
167
|
+
self.assertEqual(n + 1, len(source))
|
|
@@ -9,6 +9,8 @@ class LRUCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
9
9
|
Cache = LRUCache
|
|
10
10
|
|
|
11
11
|
def test_lru(self):
|
|
12
|
+
import copy
|
|
13
|
+
|
|
12
14
|
cache = LRUCache[int, int](maxsize=2)
|
|
13
15
|
|
|
14
16
|
cache[1] = 1
|
|
@@ -21,6 +23,8 @@ class LRUCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
21
23
|
self.assertNotIn(1, cache)
|
|
22
24
|
|
|
23
25
|
cache[2]
|
|
26
|
+
# a shallow copy evicts in the same order, on its own
|
|
27
|
+
self.assertEqual((3, 3), copy.copy(cache).popitem())
|
|
24
28
|
cache[4] = 4
|
|
25
29
|
self.assertEqual(len(cache), 2)
|
|
26
30
|
self.assertEqual(cache[2], 2)
|
|
@@ -101,3 +101,18 @@ class RRCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
101
101
|
|
|
102
102
|
with self.assertRaises(KeyError):
|
|
103
103
|
cache.popitem()
|
|
104
|
+
|
|
105
|
+
def test_rr_copy(self):
|
|
106
|
+
import copy
|
|
107
|
+
|
|
108
|
+
source = RRCache[int, int](maxsize=3, choice=min)
|
|
109
|
+
source.update({1: 1, 2: 2, 3: 3})
|
|
110
|
+
|
|
111
|
+
# the copy has its own keys to choose from
|
|
112
|
+
cache = copy.copy(source)
|
|
113
|
+
del cache[1]
|
|
114
|
+
self.assertEqual((2, 2), cache.popitem())
|
|
115
|
+
self.assertEqual((1, 1), source.popitem())
|
|
116
|
+
self.assertEqual((2, 2), source.popitem())
|
|
117
|
+
self.assertEqual((3, 3), source.popitem())
|
|
118
|
+
self.assertEqual((3, 3), cache.popitem())
|
|
@@ -420,3 +420,73 @@ class TLRUCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
420
420
|
sized["abc"] = "abc"
|
|
421
421
|
self.assertEqual("abc", sized["abc"])
|
|
422
422
|
self.assertEqual(3, sized.currsize)
|
|
423
|
+
|
|
424
|
+
def test_tlru_copy(self):
|
|
425
|
+
import copy
|
|
426
|
+
|
|
427
|
+
source = TLRUCache[int, int, int](
|
|
428
|
+
maxsize=3, ttu=lambda _key, value, time: time + value, timer=Timer()
|
|
429
|
+
)
|
|
430
|
+
source[1] = 3
|
|
431
|
+
source[2] = 1
|
|
432
|
+
source[3] = 2
|
|
433
|
+
source[1] = 2 # leaves a removed item behind, least recently used is 2
|
|
434
|
+
|
|
435
|
+
cache = copy.copy(source)
|
|
436
|
+
self.assertEqual(list(source), list(cache))
|
|
437
|
+
|
|
438
|
+
# the copy evicts as its source would, on its own
|
|
439
|
+
cache[4] = 5
|
|
440
|
+
self.assertEqual([1, 3, 4], sorted(cache))
|
|
441
|
+
self.assertEqual([1, 2, 3], sorted(source))
|
|
442
|
+
|
|
443
|
+
# items expire in the copy as in its source
|
|
444
|
+
cache.timer.tick()
|
|
445
|
+
self.assertEqual([1, 3], sorted(source))
|
|
446
|
+
self.assertEqual([1, 3, 4], sorted(cache))
|
|
447
|
+
source.timer.tick()
|
|
448
|
+
self.assertEqual([], list(source))
|
|
449
|
+
self.assertEqual([4], list(cache))
|
|
450
|
+
|
|
451
|
+
def test_tlru_deepcopy_timer(self):
|
|
452
|
+
import copy
|
|
453
|
+
|
|
454
|
+
class DeepCopyTimer(Timer):
|
|
455
|
+
def __deepcopy__(self, memo):
|
|
456
|
+
return copy.copy(self)
|
|
457
|
+
|
|
458
|
+
source = TLRUCache[int, int, int](
|
|
459
|
+
maxsize=2, ttu=lambda _, v, t: t + v, timer=DeepCopyTimer()
|
|
460
|
+
)
|
|
461
|
+
source[1] = 1
|
|
462
|
+
|
|
463
|
+
# a timer may define __deepcopy__ itself
|
|
464
|
+
cache = copy.deepcopy(source)
|
|
465
|
+
self.assertEqual([1], list(cache))
|
|
466
|
+
|
|
467
|
+
# the copy has a timer of its own
|
|
468
|
+
cache.timer.tick()
|
|
469
|
+
self.assertEqual([], list(cache))
|
|
470
|
+
self.assertEqual([1], list(source))
|
|
471
|
+
|
|
472
|
+
def test_tlru_iter_modify(self):
|
|
473
|
+
cache = TLRUCache[int, int, int](
|
|
474
|
+
maxsize=6, ttu=lambda _, v, t: t + 2, timer=Timer()
|
|
475
|
+
)
|
|
476
|
+
cache.update({1: 1, 2: 2, 3: 3})
|
|
477
|
+
|
|
478
|
+
# items inserted while iterating are not visited
|
|
479
|
+
keys = []
|
|
480
|
+
for key in cache:
|
|
481
|
+
keys.append(key)
|
|
482
|
+
cache[key + 10] = key
|
|
483
|
+
self.assertEqual([1, 2, 3], keys)
|
|
484
|
+
self.assertEqual([1, 2, 3, 11, 12, 13], list(cache))
|
|
485
|
+
|
|
486
|
+
# items removed while iterating are skipped
|
|
487
|
+
keys = []
|
|
488
|
+
for key in cache:
|
|
489
|
+
keys.append(key)
|
|
490
|
+
cache.clear()
|
|
491
|
+
self.assertEqual([1], keys)
|
|
492
|
+
self.assertEqual([], list(cache))
|
|
@@ -287,3 +287,72 @@ class TTLCacheTest(unittest.TestCase, CacheTestMixin):
|
|
|
287
287
|
sized["abc"] = "abc"
|
|
288
288
|
self.assertEqual("abc", sized["abc"])
|
|
289
289
|
self.assertEqual(3, sized.currsize)
|
|
290
|
+
|
|
291
|
+
def test_ttl_copy(self):
|
|
292
|
+
import copy
|
|
293
|
+
|
|
294
|
+
source = TTLCache[int, int, int](maxsize=3, ttl=2, timer=Timer())
|
|
295
|
+
source[1] = 1
|
|
296
|
+
source[2] = 2
|
|
297
|
+
source.timer.tick()
|
|
298
|
+
source[3] = 3
|
|
299
|
+
self.assertEqual(1, source[1]) # least recently used is now 2
|
|
300
|
+
|
|
301
|
+
cache = copy.copy(source)
|
|
302
|
+
self.assertEqual([1, 2, 3], list(cache))
|
|
303
|
+
|
|
304
|
+
# the copy evicts as its source would, on its own
|
|
305
|
+
cache[4] = 4
|
|
306
|
+
self.assertEqual([1, 3, 4], list(cache))
|
|
307
|
+
self.assertEqual([1, 2, 3], list(source))
|
|
308
|
+
|
|
309
|
+
# the timer is shared, but not the caches' use of it
|
|
310
|
+
self.assertIsNot(source.timer, cache.timer)
|
|
311
|
+
with source.timer:
|
|
312
|
+
cache.timer.tick()
|
|
313
|
+
self.assertEqual(1, source.timer())
|
|
314
|
+
self.assertEqual(2, cache.timer())
|
|
315
|
+
self.assertEqual(2, source.timer())
|
|
316
|
+
|
|
317
|
+
# items expire in the copy as in its source
|
|
318
|
+
self.assertEqual([3, 4], list(cache))
|
|
319
|
+
self.assertEqual([3], list(source))
|
|
320
|
+
|
|
321
|
+
def test_ttl_deepcopy_timer(self):
|
|
322
|
+
import copy
|
|
323
|
+
|
|
324
|
+
class DeepCopyTimer(Timer):
|
|
325
|
+
def __deepcopy__(self, memo):
|
|
326
|
+
return copy.copy(self)
|
|
327
|
+
|
|
328
|
+
source = TTLCache[int, int, int](maxsize=2, ttl=1, timer=DeepCopyTimer())
|
|
329
|
+
source[1] = 1
|
|
330
|
+
|
|
331
|
+
# a timer may define __deepcopy__ itself
|
|
332
|
+
cache = copy.deepcopy(source)
|
|
333
|
+
self.assertEqual([1], list(cache))
|
|
334
|
+
|
|
335
|
+
# the copy has a timer of its own
|
|
336
|
+
cache.timer.tick()
|
|
337
|
+
self.assertEqual([], list(cache))
|
|
338
|
+
self.assertEqual([1], list(source))
|
|
339
|
+
|
|
340
|
+
def test_ttl_iter_modify(self):
|
|
341
|
+
cache = TTLCache[int, int, int](maxsize=6, ttl=2, timer=Timer())
|
|
342
|
+
cache.update({1: 1, 2: 2, 3: 3})
|
|
343
|
+
|
|
344
|
+
# items inserted while iterating are not visited
|
|
345
|
+
keys = []
|
|
346
|
+
for key in cache:
|
|
347
|
+
keys.append(key)
|
|
348
|
+
cache[key + 10] = key
|
|
349
|
+
self.assertEqual([1, 2, 3], keys)
|
|
350
|
+
self.assertEqual([1, 2, 3, 11, 12, 13], list(cache))
|
|
351
|
+
|
|
352
|
+
# items removed while iterating are skipped
|
|
353
|
+
keys = []
|
|
354
|
+
for key in cache:
|
|
355
|
+
keys.append(key)
|
|
356
|
+
cache.clear()
|
|
357
|
+
self.assertEqual([1], keys)
|
|
358
|
+
self.assertEqual([], list(cache))
|
cachetools-8.0.0/AGENTS.md
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
# cachetools
|
|
2
|
-
|
|
3
|
-
Memoizing collections and decorators, including `functools.lru_cache` variants. Pure
|
|
4
|
-
Python ≥ 3.11, no runtime dependencies, `src/` layout, inline type stubs (`*.pyi`,
|
|
5
|
-
`py.typed`). Single maintainer; `master` is the release branch, `dev/vX.Y.Z` branches
|
|
6
|
-
prepare bugfix releases and `develop` (the 8.0 line) is rebased onto the latest one.
|
|
7
|
-
Code reviews follow `.github/copilot-instructions.md`.
|
|
8
|
-
|
|
9
|
-
## Commands
|
|
10
|
-
|
|
11
|
-
Run everything through `tox`, never bare `pytest`, `ruff` or `pyright`:
|
|
12
|
-
|
|
13
|
-
```bash
|
|
14
|
-
tox -p auto # all environments, as CI does
|
|
15
|
-
tox -e py -- tests/test_ttl.py -k expire # tests; posargs go to pytest
|
|
16
|
-
tox -e pyright,ruff,ruff-format,docs,doctest # stubs, lint, format, docs
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
CI (GitHub Actions on `tkem/cachetools`, every push) runs CPython 3.11–3.15,
|
|
20
|
-
free-threaded 3.13t–3.15t and PyPy 3.11; without `gh`, check runs via
|
|
21
|
-
`https://api.github.com/repos/tkem/cachetools/actions/runs?branch=<branch>`. Branch
|
|
22
|
-
coverage is 100 %; on 3.13+ only the pre-3.13 `@classmethod` line in
|
|
23
|
-
`_MethodDescriptor.__get__` is uncovered.
|
|
24
|
-
|
|
25
|
-
## Code Style
|
|
26
|
-
|
|
27
|
-
- No annotations in `.py` files; types live in the `.pyi` stubs. Decorator
|
|
28
|
-
`@overload`s come in the order keyword-only `info: Literal[True]`,
|
|
29
|
-
`info: Literal[False] = ...` (default), positional `Literal[True]`.
|
|
30
|
-
- Prefer clarity and performance over DRY: one wrapper class per lock/condition/info
|
|
31
|
-
combination in `_decorator.py`, `_cached.py` and `_cachedmethod.py`, and the key
|
|
32
|
-
functions in `keys.py` are written out in full. Apply a change to **all** variants.
|
|
33
|
-
- Keep hot paths free of avoidable Python-level calls. Look links and items up with
|
|
34
|
-
`.get()` and test for `None` instead of catching `KeyError` per new key (~200 ns).
|
|
35
|
-
- Wrapper `__call__` methods, `_Unbound.__call__`, `_MethodDescriptor.__call__` and
|
|
36
|
-
the key functions take their receiver positional-only (`self, /`), so wrapped
|
|
37
|
-
callables may take a keyword argument named `self`; keep it that way everywhere.
|
|
38
|
-
- Stubs: never annotate `self` in an `__init__` overload with class-scoped type
|
|
39
|
-
variables (pyright warns, and `tox` does not fail on warnings, so check for
|
|
40
|
-
`0 warnings`); an overload without `timer` relies on the `_TT` default instead.
|
|
41
|
-
- Unsupported use raises `TypeError` before anything is cached, chained `from None`;
|
|
42
|
-
a store that fails with `ValueError` (value too large) is swallowed and the
|
|
43
|
-
computed value returned.
|
|
44
|
-
- Docs (`docs/index.rst`, doctested): wrap prose at column 70, two spaces after a
|
|
45
|
-
sentence, single backticks for parameters and `:meth:`/`:func:`/`:exc:` roles. Keep
|
|
46
|
-
`README.rst` examples in sync with it.
|
|
47
|
-
|
|
48
|
-
## Architecture Constraints
|
|
49
|
-
|
|
50
|
-
- A value's size must not change after insertion. With the default `getsizeof` the
|
|
51
|
-
size dict is `None` and `getsizeof()` is never called: keep that fast path.
|
|
52
|
-
- Cache subclasses override `__setitem__`, `__delitem__`, `popitem()`, `clear()` and
|
|
53
|
-
optionally `__getitem__`; after the parent `__getitem__`, check the subclass's own
|
|
54
|
-
bookkeeping, not `key in self`, since `__missing__` may not store the item.
|
|
55
|
-
`popitem()` evicts via `del self[key]`, so `__delitem__` overrides see evictions.
|
|
56
|
-
- `items()` and `values()` read through `__getitem__` and count as a use of every item;
|
|
57
|
-
inspect state with `list(cache)`. `LFUCache` ties discard the least recently used key
|
|
58
|
-
(documented since 7.3) in O(1): keep the `OrderedDict` per use count (#461).
|
|
59
|
-
- Timed caches expire lazily (`__len__`, `__repr__` and `currsize` call `expire()`,
|
|
60
|
-
`clear()` does not); every insert and `popitem()` must keep calling that hook.
|
|
61
|
-
- Decorator wrappers are objects, not functions; `_WrapperBase` runs
|
|
62
|
-
`update_wrapper()` *before* setting its public attributes (stacked decorators).
|
|
63
|
-
- A `condition` passed with a separate `lock` must be created with that lock
|
|
64
|
-
(`Condition(lock)`), as `wait()` and `notify_all()` run under `lock`; not checked.
|
|
65
|
-
- `@cachedmethod` stores per-instance wrappers in `obj.__dict__`; `super()` lookups and
|
|
66
|
-
lookups after `del Cls.method` use `obj.__dict__["__cachetools_cachedmethods"]`.
|
|
67
|
-
`cache_key` is `partial(key, obj)`, not `types.MethodType`, which on PyPy accepts a
|
|
68
|
-
non-callable `key`. Pickling and deep-copying such objects (#417) and
|
|
69
|
-
`create_autospec()` on their classes (#443) must keep working;
|
|
70
|
-
`_MethodDescriptor._lookup` must stay importable.
|
|
71
|
-
- Key functions return plain tuples, `args` itself without kwargs; `_HashedTuple`
|
|
72
|
-
survives only as the kwargs separator and to load keys pickled by 7.x.
|
|
73
|
-
|
|
74
|
-
## Testing
|
|
75
|
-
|
|
76
|
-
- New behavior needs tests under `tests/`; user-visible features need docs in
|
|
77
|
-
`docs/index.rst`. One `TestCase` per cache type on `CacheTestMixin`; TTL tests use a
|
|
78
|
-
manual `Timer`. Objects pickled by name must be reachable from module level.
|
|
79
|
-
- Stub checks need concrete annotated tests without `# type: ignore`, since
|
|
80
|
-
`test_func.py` calls decorators via `Callable[..., Any]`.
|
|
81
|
-
- Threading tests use real `Lock`/`Condition` objects (`WaitCondition(lock)` forces a
|
|
82
|
-
contended `wait()`), join with `TIMEOUT` and assert the thread finished.
|
|
83
|
-
- Performance: `timeit`, best of 7, on a pinned core (`taskset`), never in a VM,
|
|
84
|
-
against a git worktree of the previous release. Never trade documented subclass
|
|
85
|
-
hooks or semantics for speed.
|
|
86
|
-
|
|
87
|
-
## Boundaries
|
|
88
|
-
|
|
89
|
-
- Never edit `CHANGELOG.rst` or bump `__version__`; both are release-only.
|
|
90
|
-
- Never promise cross-version pickle compatibility or build on the byte format; any
|
|
91
|
-
release, even a bugfix, may change it.
|
|
92
|
-
- Do not re-raise the *Maintainer Decisions* in `.github/copilot-instructions.md`.
|
|
93
|
-
|
|
94
|
-
## Git
|
|
95
|
-
|
|
96
|
-
- PRs reference an open issue (except trivial fixes), in separate commits:
|
|
97
|
-
`Fix #123: ...`, `Tests for #123: ...`, `Docs for #123: ...`.
|
|
98
|
-
- Run `tox -p auto` before pushing. Update this file in the same PR that changes a
|
|
99
|
-
convention, and keep it under 100 lines.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|