cachetools 8.0.1__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.
Files changed (38) hide show
  1. {cachetools-8.0.1 → cachetools-8.0.2}/CHANGELOG.rst +12 -0
  2. {cachetools-8.0.1/src/cachetools.egg-info → cachetools-8.0.2}/PKG-INFO +1 -1
  3. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/__init__.py +38 -23
  4. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/__init__.pyi +2 -2
  5. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/_cached.py +2 -2
  6. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/_cachedmethod.py +4 -4
  7. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/_decorator.py +0 -2
  8. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/_descriptor.py +12 -12
  9. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/func.py +2 -3
  10. {cachetools-8.0.1 → cachetools-8.0.2/src/cachetools.egg-info}/PKG-INFO +1 -1
  11. {cachetools-8.0.1 → cachetools-8.0.2}/tests/__init__.py +12 -0
  12. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_tlru.py +43 -0
  13. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_ttl.py +39 -0
  14. {cachetools-8.0.1 → cachetools-8.0.2}/LICENSE +0 -0
  15. {cachetools-8.0.1 → cachetools-8.0.2}/MANIFEST.in +0 -0
  16. {cachetools-8.0.1 → cachetools-8.0.2}/README.rst +0 -0
  17. {cachetools-8.0.1 → cachetools-8.0.2}/docs/conf.py +0 -0
  18. {cachetools-8.0.1 → cachetools-8.0.2}/docs/index.rst +0 -0
  19. {cachetools-8.0.1 → cachetools-8.0.2}/pyproject.toml +0 -0
  20. {cachetools-8.0.1 → cachetools-8.0.2}/setup.cfg +0 -0
  21. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/func.pyi +0 -0
  22. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/keys.py +0 -0
  23. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/keys.pyi +0 -0
  24. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools/py.typed +0 -0
  25. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools.egg-info/SOURCES.txt +0 -0
  26. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools.egg-info/dependency_links.txt +0 -0
  27. {cachetools-8.0.1 → cachetools-8.0.2}/src/cachetools.egg-info/top_level.txt +0 -0
  28. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_cache.py +0 -0
  29. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_cached.py +0 -0
  30. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_cachedmethod.py +0 -0
  31. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_fifo.py +0 -0
  32. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_func.py +0 -0
  33. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_keys.py +0 -0
  34. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_lfu.py +0 -0
  35. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_lru.py +0 -0
  36. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_rr.py +0 -0
  37. {cachetools-8.0.1 → cachetools-8.0.2}/tests/test_threading.py +0 -0
  38. {cachetools-8.0.1 → cachetools-8.0.2}/tox.ini +0 -0
@@ -1,3 +1,15 @@
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
+
1
13
  v8.0.1 (2026-11-17)
2
14
  ===================
3
15
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cachetools
3
- Version: 8.0.1
3
+ Version: 8.0.2
4
4
  Summary: Extensible memoizing collections and decorators
5
5
  Author-email: Thomas Kemmer <tkemmer@computer.org>
6
6
  Maintainer-email: Thomas Kemmer <tkemmer@computer.org>
@@ -13,7 +13,7 @@ __all__ = (
13
13
  "cachedmethod",
14
14
  )
15
15
 
16
- __version__ = "8.0.1"
16
+ __version__ = "8.0.2"
17
17
 
18
18
  import collections
19
19
  import collections.abc
@@ -113,6 +113,10 @@ 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
+
116
120
  def __copy__(self):
117
121
  cls = type(self)
118
122
  copy = cls.__new__(cls)
@@ -123,7 +127,7 @@ class Cache(collections.abc.MutableMapping):
123
127
  return copy
124
128
 
125
129
  # Note that we cannot simply inherit get(), pop() and setdefault()
126
- # from MutableMapping, since these rely on __getitem__ throwing a
130
+ # from MutableMapping, since these rely on __getitem__ raising a
127
131
  # KeyError on cache miss. This is not the case if __missing__ is
128
132
  # implemented for a Cache subclass, so we have to roll our own,
129
133
  # somewhat less elegant versions.
@@ -251,7 +255,7 @@ class LFUCache(Cache):
251
255
 
252
256
  def __getitem__(self, key, cache_getitem=Cache.__getitem__):
253
257
  value = cache_getitem(self, key)
254
- if key in self.__links: # __missing__ may not store item
258
+ if key in self.__links: # __missing__ may not store the item
255
259
  self.__touch(key)
256
260
  return value
257
261
 
@@ -305,7 +309,7 @@ class LFUCache(Cache):
305
309
  curr = root.next
306
310
  if curr is root:
307
311
  raise KeyError("%s is empty" % type(self).__name__) from None
308
- key = next(iter(curr.keys)) # remove the "oldest" element
312
+ key = next(iter(curr.keys)) # least recently used key with the lowest use count
309
313
  value = Cache.__getitem__(self, key)
310
314
  del self[key]
311
315
  return (key, value)
@@ -346,7 +350,7 @@ class LRUCache(Cache):
346
350
  value = cache_getitem(self, key)
347
351
  try:
348
352
  self.__order.move_to_end(key)
349
- except KeyError: # __missing__ may not store item
353
+ except KeyError: # __missing__ may not store the item
350
354
  pass
351
355
  return value
352
356
 
@@ -462,6 +466,12 @@ class _TimedCache(Cache):
462
466
  def __copy__(self):
463
467
  return _TimedCache._Timer(self.__timer)
464
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
+
465
475
  def __reduce__(self):
466
476
  return _TimedCache._Timer, (self.__timer,)
467
477
 
@@ -511,9 +521,9 @@ class _TimedCache(Cache):
511
521
  return Cache.setdefault(self, *args, **kwargs)
512
522
 
513
523
  def clear(self):
514
- # Subclasses must override to also reset their own time-tracking
515
- # structures; we do not call expire() here since clear() should
516
- # 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.
517
527
  Cache.clear(self)
518
528
 
519
529
  def expire(self, time=None): # pragma: no cover
@@ -594,14 +604,15 @@ class TTLCache(_TimedCache):
594
604
  raise KeyError(key)
595
605
 
596
606
  def __iter__(self):
597
- root = self.__root
598
- curr = root.next
599
- while curr is not root:
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)):
600
611
  # "freeze" time for iterator access
601
612
  with self.timer as time:
602
- if time < curr.expires:
603
- yield curr.key
604
- curr = curr.next
613
+ link = self.__links.get(key)
614
+ if link is not None and time < link.expires:
615
+ yield key
605
616
 
606
617
  def __copy__(self):
607
618
  copy = super().__copy__()
@@ -726,12 +737,12 @@ class TLRUCache(_TimedCache):
726
737
  self.expire(time)
727
738
  expires = self.__ttu(key, value, time)
728
739
  if not (time < expires):
729
- # updating an existing item with an already expired
730
- # one should remove the existing item
740
+ # Updating an existing item with an already expired
741
+ # one should remove the existing item.
731
742
  return self.__delitem(key)
732
743
  cache_setitem(self, key, value)
733
- # removing an existing item would break the heap structure, so
734
- # 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.
735
746
  items = self.__items
736
747
  item = items.get(key)
737
748
  if item is not None:
@@ -742,7 +753,7 @@ class TLRUCache(_TimedCache):
742
753
 
743
754
  def __delitem__(self, key, cache_delitem=Cache.__delitem__):
744
755
  with self.timer as time:
745
- # no self.expire() for performance reasons, e.g. self.clear() [#67]
756
+ # no self.expire() for performance reasons, e.g. when evicting [#67]
746
757
  cache_delitem(self, key)
747
758
  item = self.__items.pop(key)
748
759
  item.removed = True
@@ -750,11 +761,15 @@ class TLRUCache(_TimedCache):
750
761
  raise KeyError(key)
751
762
 
752
763
  def __iter__(self):
753
- for curr in self.__order:
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)):
754
768
  # "freeze" time for iterator access
755
769
  with self.timer as time:
756
- if time < curr.expires and not curr.removed:
757
- yield curr.key
770
+ item = self.__items.get(key)
771
+ if item is not None and time < item.expires:
772
+ yield key
758
773
 
759
774
  def __copy__(self):
760
775
  copy = super().__copy__()
@@ -849,7 +864,7 @@ def cached(cache, key=keys.hashkey, lock=None, condition=None, info=False):
849
864
  """
850
865
  from ._cached import _wrapper
851
866
 
852
- if cache is None: # no longer supported since v8.0.0
867
+ if cache is None: # unsupported since v8.0.0
853
868
  raise TypeError("cache must not be None")
854
869
 
855
870
  def decorator(func):
@@ -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
- # pyright cannot match the self-typed base overload; each return type is
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,8 +27,8 @@ 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
- # update first, so func.__dict__ cannot override wrapper state,
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
@@ -37,10 +37,10 @@ class _WrapperBase:
37
37
  self.cache_key = functools.partial(key, obj)
38
38
 
39
39
  def __reduce__(self):
40
- # rebuild via the descriptor instead of pickling unpicklable
41
- # internals, e.g. __wrapped__, lock/cond closures; note that
42
- # this will also reset hits and misses counts for *Info*
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
- # before Python 3.13, @classmethod calls __get__(cls, type(cls))
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
- # replace descriptor instance with wrapper in instance dict; in case
52
- # of a race condition where another thread already replaced the
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,16 +70,16 @@ class _MethodDescriptor:
70
70
  return wrapper
71
71
 
72
72
  def __reduce__(self):
73
- # pickle and copy by reference, so wrappers and their keys in
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
- # called by whatever wraps the descriptor: @classmethod since Python
82
- # 3.13, @staticmethod, @property or any other function decorator
81
+ # Called by whatever wraps the descriptor: @classmethod since Python
82
+ # 3.13, @staticmethod, @property or any other function decorator.
83
83
  def __call__(self, /, *args, **kwargs):
84
84
  raise TypeError(
85
85
  "Cannot call @cachedmethod descriptor directly: @cachedmethod must "
@@ -95,7 +95,7 @@ class _MethodDescriptor:
95
95
 
96
96
  def __instance_dict_error(self, obj, error):
97
97
  if isinstance(error, AttributeError):
98
- # not all objects have __dict__ (e.g. class defines slots)
98
+ # not all objects have __dict__ (e.g. if the class defines __slots__)
99
99
  msg = (
100
100
  f"No '__dict__' attribute on {type(obj).__name__!r} "
101
101
  f"instance to cache {self.__attrname!r}"
@@ -137,8 +137,8 @@ class _Unbound:
137
137
  return self
138
138
  return self.__descriptor.__get__(obj)
139
139
 
140
- # Receiver is taken from *args so autospec'd instances accept any call,
141
- # 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.
142
142
  def __call__(self, /, *args, **kwargs):
143
143
  if args:
144
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
- # like functools.lru_cache, this has to be thread-safe;
25
- # additionally, this also prevents cache stampede scenarios
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cachetools
3
- Version: 8.0.1
3
+ Version: 8.0.2
4
4
  Summary: Extensible memoizing collections and decorators
5
5
  Author-email: Thomas Kemmer <tkemmer@computer.org>
6
6
  Maintainer-email: Thomas Kemmer <tkemmer@computer.org>
@@ -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
 
@@ -447,3 +447,46 @@ class TLRUCacheTest(unittest.TestCase, CacheTestMixin):
447
447
  source.timer.tick()
448
448
  self.assertEqual([], list(source))
449
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))
@@ -317,3 +317,42 @@ class TTLCacheTest(unittest.TestCase, CacheTestMixin):
317
317
  # items expire in the copy as in its source
318
318
  self.assertEqual([3, 4], list(cache))
319
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))
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