Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/cachetools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,10 +625,26 @@ def __getitem__(self, key, cache_getitem=Cache.__getitem__):
else:
return cache_getitem(self, key)

def __setitem__(self, key, value, cache_setitem=Cache.__setitem__):
def __setitem__(
self,
key,
value,
cache_setitem=Cache.__setitem__,
cache_delitem=Cache.__delitem__,
):
with self.timer as time:
expires = self.__ttu(key, value, time)
if not (time < expires):
# The new value is already expired, so it is not stored.
# If the key still holds a previous (possibly still valid)
# value, drop it as well -- otherwise the assignment would
# be silently ignored and the stale value would persist.
try:
self.__items.pop(key).removed = True
except KeyError:
pass
else:
cache_delitem(self, key)
return # skip expired items
self.expire(time)
cache_setitem(self, key, value)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_tlru.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,26 @@ def ttu(_k, _v, t):
self.assertEqual(cache[4], 4)
self.assertEqual(cache[5], 5)

def test_overwrite_existing_with_expired(self):
# Overwriting an existing key with an already-expired value must not
# silently retain the previous value: the assignment cannot store the
# new (dead-on-arrival) value, so the key has to be evicted instead.
def ttu(_k, value, t):
return t + value

cache = TLRUCache[int, int, int](maxsize=2, ttu=ttu, timer=Timer())
cache[1] = 5
self.assertEqual(cache[1], 5)
self.assertEqual(len(cache), 1)
self.assertEqual(cache.currsize, 1)

cache[1] = 0 # ttu -> t, i.e. not (t < t): immediately expired
self.assertNotIn(1, cache)
self.assertIsNone(cache.get(1))
self.assertEqual(len(cache), 0)
self.assertEqual(cache.currsize, 0)
self.assertEqual(set(cache), set())

def test_ttu_expire(self):
def ttu(_k, _v, t):
return t + 3
Expand Down