I successfully implemented a granular cache_clear()
for a Python redis backed lru cache decorator - see gist. This was a totally different implementation of lru_cache
than the one that is shipped with Python 3, I could understand it's internals and make the necessary changes.
Specifically, cache_clear()
was enhanced so that if you pass parameters the cache is cleared partially - only for that particular call signature. This does indeed allow for more granular cache clearing.
I learnt something deep along the way, which sheds some light on this discussion and may be a reason why Python 3 did not adopt granular cache clearing.
I discovered that such an enhanced cache_clear()
behaviour needed to be used with great care since whilst
e.g. f(1)
and f(param=1)
mean the same, the lru caching system will cache those
two calls as separate entries. Then when you invalidate one style of call with
f.cache_clear(1)
this leaves the other style of call f(param=1)
still cached and
returning stale values - even though semantically these two styles of call are the
same. So if you do use cache_clear granularly, make sure you call it repeatedly for
all possible parameter signatures that you might have used e.g. f.cache_clear(1)
;
f.cache_clear(param=1)
.
I suppose there might be an algorithm that can figure out all the possible permutations of parameters (*args, **kwargs)
that are equivalent? Then such a granular cache clearing approach would be much safer to use.