Memoization and encapsulation

Tom Anderson twic at urchin.earth.li
Sun Jan 1 16:57:24 EST 2006


On Sat, 31 Dec 2005 skip at pobox.com wrote:

>    just> I actually prefer such a global variable to the default arg
>    just> trick. The idiom I generally use is:
>
>    just> _cache = {}
>    just> def func(x):
>    just>     result = _cache.get(x)
>    just>     if result is None:
>    just>         result = x + 1  # or a time consuming calculation...
>    just>         _cache[x] = result
>    just>     return result
>
> None of the responses I've seen mention the use of decorators such as the
> one shown here:
>
>    http://wiki.python.org/moin/PythonDecoratorLibrary
>
> While wrapping one function in another is obviously a bit slower, you can
> memoize any function without tweaking its source.

I'd definitely say this is the way to go.

def memoised(fn):
 	cache = {}
 	def memoised_fn(*args):
 		if args in cache:
 			return cache[args]
 		else:
 			rtn = fn(*args)
 			cache[args] = rtn
 			return rtn
 	return memoised_fn

@memoised
def func(x):
 	return x + 1 # or a time-consuming calculation

tom

-- 
Exceptions say, there was a problem. Someone must deal with it. If you
won't deal with it, I'll find someone who will.



More information about the Python-list mailing list