So I am using LRU Cache
from functools
I use the decorator @lru_cache
to cache certain functions.
I would like to have a way to check the contents of the cache
object from a file.
I tried requesting for a function like this from the CPython github library but the issue won’t be proceeding.
So I need some help/guidance. Bottom line is I need to see the contents of the cache object.
You could copy the Python implementation of lru_cache
from the standard library in Lib/functools.py (and include the proper license info) and add access to the cache
Simplest version of that would be to just add a line
wrapper.cache = cache
before the wrapper is returned at the end
2 Likes
Wombat
(Zeke W)
April 3, 2025, 3:04am
3
Some ideas for you.
Consider adding logging to the cached function:
@functools.lru_cache
def increment(x):
y = x + 1
logging.debug("Incrementing %r to %r", x, y)
return y
Make your own lru_cache replacement where the internals are visible. This is a minor edit of the examples in the collections docs .
from collections import OrderedDict
class LRU:
def __init__(self, func):
self.cache = OrderedDict()
self.func = func
self.maxsize = 128
def __call__(self, *args):
if args in self.cache:
self.cache.move_to_end(args)
return self.cache[args]
result = self.func(*args)
self.cache[args] = result
if len(self.cache) > self.maxsize:
self.cache.popitem(last=False)
return result
@LRU
def func(x):
return x + 1