[Question] Remove/invalidate a single item from cache
Closed this issue · 3 comments
Feijo commented
Is there a way to remove a particular item from the cache, rather than clearing the whole cache?
Something like this
cache = LRUCache(maxsize=32)
lock = RLock()
@cached(cache, lock=lock)
def get_data_for_user(user_id):
return [ 'Item 1', 'Item 2', 'Item 3' ]
user_1_data = get_data_for_user(1)
user_2_data = get_data_for_user(2)
user_3_data = get_data_for_user(3)
with lock:
cache.remove(1) # This would invalidate user_id = 1 cached data
tkem commented
Did you try
del cache[1]
Feijo commented
Hey, sure did. This is the result:
File "C:\Python38\lib\site-packages\cachetools\lru.py", line 23, in __delitem__
cache_delitem(self, key)
File "C:\Python38\lib\site-packages\cachetools\cache.py", line 61, in __delitem__
del self.__data[key]
KeyError: 1
tkem commented
My bad. Since the decorator uses hashkey
as the default key function, the proper way to delete a cache item is
del cache[hashkey(1)]
Not really intuitive, so this should probably be mentioned in the docs.