Carlos Pinzón Carlos Pinzón - 20 days ago 5
Python Question

How to export lru_cache in python?

I'm using the decorator

@lru_cache(maxsize=None)
from
functools
, and I wan't to save the memoized values to a file in order to avoid re-computing them each time I run the code.

Is there an elegant way of doing this different from printing args and values to a file and then reading them?

Answer

@Carlos Pinzón, posted as an answer as you requested: functools.lru_cache() is designed to work with arbitrary positional and keyword arguments, and possibly a maximum cache size. If you don't need those features, it isn't too difficult to roll your own cache (aka memoize) decorator. The cache is just a dictionary, so you can provide a function to save it to disk as a pickle (or json if you want to be able to look at it) and reload it later. The lru_cache sourcecode is also available; modify it to suit your needs.