qdyn.memoize module

Decorator for function memoization

Memoization (sic!) is the concept caching the result of a function, so that if the function is called again with the same parameters, the result is returned directly, without recalculating it.

>>> from click import echo
>>> @memoize
... def f(a,b,c):
...     return str(a) + str(b) + str(c)
...
>>> echo(f(1,2,3))
123
>>> echo(f([], None, (1,2,3)))
[]None(1, 2, 3)
>>> len(f._combined_cache())
2

The memoize decorator allows for the possibility to write the cache to disk and to reload it at a later time

>>> f.dump('memoize.dump')
>>> f.clear()
>>> len(f._combined_cache())
0
>>> f.load('memoize.dump')
>>> len(f._combined_cache())
2
>>> import os
>>> os.unlink('memoize.dump')

Summary

Classes:

memoize

Decorator.

Reference

class qdyn.memoize.memoize(func)[source]

Bases: object

Decorator. Caches a function’s return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated).

Create a memoized version of the given function

clear()[source]

Forget all cached results

dump(filename)[source]

Write memoization cache to the given file or file-like object

load(filename, raise_error=False)[source]

Load dumped data from the given file and update the memoization cache

If raise_error is True, raise an IOError if the file does not exist. Otherwise, simply leave cache unchanged.

add_to_cache(result, args=None, kwargs=None)[source]

Add the known result for a given set of args and kwargs to the cache. One case where this is useful is when calling a function as part of a multiprocessing pool, or another parallelization method that does not have shared memory. In this situation, memoization will fail, but the results may be added to the cache later on.

__repr__()[source]

Return the function’s docstring.