Home | Articles | CV (pdf | short)
<2008-04-17> by Lorenzo


Recently, from a discussion on the scipy-user group I discovered a very elegant way to code a function with memory.

Let's state the problem. Suppose you need a function that remembers, for each time it has been called, the input parameters and its output. This can be very useful in many different situations:

The function's memory can be as long as the program's running time, or it can be "permanent" if hard-coded in a file. Starting from here I've put together a couple of useful classes in python that can be used as decorators.

They are used as follows:

# function to memoize
def f(x):
    return x**2

# memoized function
memoized_f = memoize(f)

# memoized function on a file
memoized_persistent_f = memoize_persistent(f)

Decorators can be used:

# function to memoize
@memoize # or @memoize_persistent
def f(x):
    return x**2

Which is equivalent to: f = memoize(f). You can download the code here.