From 7be40f090e4a643dde62486becb2ab90aa166011 Mon Sep 17 00:00:00 2001 From: Thomas Kemmer Date: Sun, 18 Aug 2024 19:30:00 +0200 Subject: [PATCH] TLRUCache.expire() returns iterable of expired (key, value) pairs. --- src/cachetools/__init__.py | 9 ++++++++- tests/test_tlru.py | 13 ++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/cachetools/__init__.py b/src/cachetools/__init__.py index 6471a85..1be3933 100644 --- a/src/cachetools/__init__.py +++ b/src/cachetools/__init__.py @@ -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 @@ -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 diff --git a/tests/test_tlru.py b/tests/test_tlru.py index 673c0c2..61ca7e9 100644 --- a/tests/test_tlru.py +++ b/tests/test_tlru.py @@ -29,7 +29,6 @@ def __init__(self, maxsize, ttu=default_ttu, **kwargs): class TLRUCacheTest(unittest.TestCase, CacheTestMixin): - Cache = TLRUTestCache def test_ttu(self): @@ -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)