Skip to content

Commit 73d1602

Browse files
committed
Minor cleanups.
1 parent 083ee5f commit 73d1602

3 files changed

Lines changed: 22 additions & 7 deletions

File tree

src/cachetools/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -422,11 +422,6 @@ def timer(self):
422422
"""The timer function used by the cache."""
423423
return self.__timer
424424

425-
def clear(self):
426-
with self.__timer as time:
427-
self.expire(time)
428-
Cache.clear(self)
429-
430425
def get(self, *args, **kwargs):
431426
with self.__timer:
432427
return Cache.get(self, *args, **kwargs)
@@ -439,6 +434,12 @@ def setdefault(self, *args, **kwargs):
439434
with self.__timer:
440435
return Cache.setdefault(self, *args, **kwargs)
441436

437+
def clear(self):
438+
# Subclasses must override to also reset their own time-tracking
439+
# structures; we do not call expire() here since clear() should
440+
# be O(1) regardless of cache contents.
441+
Cache.clear(self)
442+
442443

443444
class TTLCache(_TimedCache):
444445
"""LRU Cache implementation with per-item time-to-live (TTL) value."""

tests/test_tlru.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ def test_tlru_clear(self):
310310
self.assertEqual(0, len(cache))
311311
self.assertEqual(0, cache.currsize)
312312

313-
# verify LRU order is reset after clear
313+
# verify LRU eviction order is reset after clear
314314
cache[3] = 3
315315
cache[4] = 4
316316
cache[3] # access 3 to make it most recently used
@@ -320,3 +320,10 @@ def test_tlru_clear(self):
320320
self.assertIn(3, cache)
321321
self.assertIn(5, cache)
322322
self.assertNotIn(4, cache)
323+
324+
# verify TLRU expiry still works after clear
325+
cache[42] = 42
326+
cache.timer.tick()
327+
cache.timer.tick()
328+
cache.timer.tick() # past TTL
329+
self.assertNotIn(42, cache)

tests/test_ttl.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def test_ttl_clear(self):
226226
self.assertEqual(0, len(cache))
227227
self.assertEqual(0, cache.currsize)
228228

229-
# verify LRU order is reset after clear
229+
# verify LRU eviction order is reset after clear
230230
cache[3] = 3
231231
cache[4] = 4
232232
cache[3] # access 3 to make it most recently used
@@ -236,3 +236,10 @@ def test_ttl_clear(self):
236236
self.assertIn(3, cache)
237237
self.assertIn(5, cache)
238238
self.assertNotIn(4, cache)
239+
240+
# verify TTL expiry still works after clear
241+
cache[42] = 42
242+
cache.timer.tick()
243+
cache.timer.tick()
244+
cache.timer.tick() # past TTL
245+
self.assertNotIn(42, cache)

0 commit comments

Comments
 (0)