On Sat, 31 Dec 2005 [EMAIL PROTECTED] 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.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to