memoization

Store the cache to a file functools.lru_cache in Python >= 3.2

Store the cache to a file functools.lru_cache in Python >= 3.2 Question: I’m using @functools.lru_cache in Python 3.3. I would like to save the cache to a file, in order to restore it when the program will be restarted. How could I do? Edit 1 Possible solution: We need to pickle any sort of callable …

Total answers: 6

memoization library for python 2.7

memoization library for python 2.7 Question: I see that python 3.2 has memoization as a decorator in functools library. http://docs.python.org/py3k/library/functools.html#functools.lru_cache Unfortunately it is not yet backported to 2.7. Is there any specific reason as why it is not available in 2.7? Is there any 3rd party library providing the same feature or should I write …

Total answers: 4

How can I memoize a class instantiation in Python?

How can I memoize a class instantiation in Python? Question: Ok, here is the real world scenario: I’m writing an application, and I have a class that represents a certain type of files (in my case this is photographs but that detail is irrelevant to the problem). Each instance of the Photograph class should be …

Total answers: 4

Trying to understand Python memoization code snippet

Trying to understand Python memoization code snippet Question: In a recent Hacker Newsletter issue, this very useful article about decorators in Python was linked. I like the article and I think I understand most of the decorator examples. However, in the non-decorator memoization example, I’m very confused by the code: def memoize(fn): stored_results = {} …

Total answers: 1

How to memoize **kwargs?

How to memoize **kwargs? Question: I haven’t seen an established way to memoize a function that takes key-word arguments, i.e. something of type def f(*args, **kwargs) since typically a memoizer has a dict to cache results for a given set of input parameters, and kwargs is a dict and hence unhashable. I have tried, following …

Total answers: 5

Caching class attributes in Python

Caching class attributes in Python Question: I’m writing a class in python and I have an attribute that will take a relatively long time to compute, so I only want to do it once. Also, it will not be needed by every instance of the class, so I don’t want to do it by default …

Total answers: 11

Is there a decorator to simply cache function return values?

Is there a decorator to simply cache function return values? Question: Consider the following: @property def name(self): if not hasattr(self, ‘_name’): # expensive calculation self._name = 1 + 1 return self._name I’m new, but I think the caching could be factored out into a decorator. Only I didn’t find one like it 😉 PS the …

Total answers: 20