Memoization and encapsulation

skip at pobox.com skip at pobox.com
Sat Dec 31 05:44:10 EST 2005


    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.

Skip



More information about the Python-list mailing list