Skip to content

Commit

Permalink
TLRUCache.expire() returns iterable of expired (key, value) pairs.
Browse files Browse the repository at this point in the history
  • Loading branch information
tkem committed Aug 18, 2024
1 parent c22fc7d commit 7be40f0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 8 additions & 1 deletion src/cachetools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,10 @@ def ttu(self):
return self.__ttu

def expire(self, time=None):
"""Remove expired items from the cache."""
"""Remove expired items from the cache and return an iterable of the
expired `(key, value)` pairs.
"""
if time is None:
time = self.timer()
items = self.__items
Expand All @@ -596,12 +599,16 @@ def expire(self, time=None):
if len(order) > len(items) * 2:
self.__order = order = [item for item in order if not item.removed]
heapq.heapify(order)
expired = []
cache_delitem = Cache.__delitem__
cache_getitem = Cache.__getitem__
while order and (order[0].removed or not (time < order[0].expires)):
item = heapq.heappop(order)
if not item.removed:
expired.append((item.key, cache_getitem(self, item.key)))
cache_delitem(self, item.key)
del items[item.key]
return expired

def popitem(self):
"""Remove and return the `(key, value)` pair least recently used that
Expand Down
13 changes: 8 additions & 5 deletions tests/test_tlru.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def __init__(self, maxsize, ttu=default_ttu, **kwargs):


class TLRUCacheTest(unittest.TestCase, CacheTestMixin):

Cache = TLRUTestCache

def test_ttu(self):
Expand Down Expand Up @@ -157,28 +156,32 @@ def test_ttu_expire(self):
self.assertEqual(2, cache[2])
self.assertEqual(3, cache[3])

cache.expire()
items = cache.expire()
self.assertEqual(set(), set(items))
self.assertEqual({1, 2, 3}, set(cache))
self.assertEqual(3, len(cache))
self.assertEqual(1, cache[1])
self.assertEqual(2, cache[2])
self.assertEqual(3, cache[3])

cache.expire(3)
items = cache.expire(3)
self.assertEqual({(1, 1)}, set(items))
self.assertEqual({2, 3}, set(cache))
self.assertEqual(2, len(cache))
self.assertNotIn(1, cache)
self.assertEqual(2, cache[2])
self.assertEqual(3, cache[3])

cache.expire(4)
items = cache.expire(4)
self.assertEqual({(2, 2)}, set(items))
self.assertEqual({3}, set(cache))
self.assertEqual(1, len(cache))
self.assertNotIn(1, cache)
self.assertNotIn(2, cache)
self.assertEqual(3, cache[3])

cache.expire(5)
items = cache.expire(5)
self.assertEqual({(3, 3)}, set(items))
self.assertEqual(set(), set(cache))
self.assertEqual(0, len(cache))
self.assertNotIn(1, cache)
Expand Down

0 comments on commit 7be40f0

Please sign in to comment.