Open
Description
Hi,
Is there a way to update/remove cache value returned by cachemethod
?
For example, in the below code,
import operator as op
from dataclasses import dataclass, field
from cachetools import TTLCache, cachedmethod
@dataclass
class A:
cache: TTLCache = field(init=False)
def __post_init__(self):
self.cache = TTLCache(maxsize=32, ttl=2 * 3600)
@cachedmethod(cache=op.attrgetter('cache'))
def compute(self, i):
print('value of i', i)
return i * 2
Suppose, I want to remove cached value for a given i
from cache, then it is not possible to do directly.
Meanwhile, I learned about hashkey
function in keys
module. But it is not exposed in cachetools __init__
, so can not be imported (of course there are hacks around it). Using this, we can updated cached value.
So, I think there could be two solutions to it,
- As
cachemethod
wraps a method to enable caching feature in it, so apart from the caching feature, it can add functionality to invalidate. For example,
a = A()
print(a.compute(10))
a.compute.remove(10) # remove can have signature *args, **kwargs. Instead of word `remove`, a more better function name can be thought
- Exposing
keys
module in cachetools__init__.py
.
from cachetools.keys import hashkey
a = A()
i = 10
print(a.compute(i))
del a.cache[hashkey(i)]
I think approach 1 would be more user friendly.