I'm using the lru_cache
decorator from functools
, and I need to invalidate only one item in it, and leave the rest unchanged. The documentation states that the __wrapped__
attribute is there for rewrapping the function with a different cache. I checked the source too, but I can't figure out how to use that. It says that
Users should only access the lru_cache through its public API: cache_info, cache_clear, and f.__wrapped__ The internals of the lru_cache are encapsulated for thread safety and to allow the implementation to change
Is is possible to remove one item from lru_cache
(safely), or should I write my own cache functionality?
lru_cache
in Python 3.9 does not even expose in Python anything but the public API - which include a cache_clear
call that will invalidate the whole cache, not just a key.
Thus, instead of finding a workaround for that, you are clearly better-off writing your own cache where you can have full control.
The __wrapped__
attribute itself is just the original function, with no lru_cache functionality at all. Actually, you can make use of it to bypass the cache for one call completely - and the function will just run with the repeated parameters as an ordinay Python function - but its response won't be cached at all.
That is, for
from functools import lru_cache
@lru_cache
def test(a):
print("side effect")
test(23)
test.__wrapped__(23)
the function body is run for both calls.