Accessing lru_cache internal dict

Viewed 212

I recently came across the functools decorators @lru_cache(maxsize=None) and @cache (in Python 3.9) for "Memoizing" hashable parameters coming into a function.

This has effectively reduced the computation time of my code significantly, so I am keeping these decorators and workflow.

According to the documentation, you get two functions as part of your wrapper: cache_info() and cache_clear(). The first one gives you information about number of hits and misses in the cache. I haven't had any luck, however, figuring out the parameters that have been stored in the cache.

Is that information available somewhere?

Basically

@lru_cache(maxsize=None)
def aCachedFunction(hasable_parameter):
    # some operations
    return retValue

Is there a way to get the retValue of a given parameter, or the cached hashable_parameters from the cache in a dict-like structure?

Something like

cachedParameters = aCachedFunction.cache_dict.keys()

hashable_parameter = "hello"
retValue = aCachedFunction.cache_dict[hashable_parameter]

Unless parameters are stored with their hash(), I guess that structure HAS to be somewhere, right? I can't find it.

0 Answers
Related