Memoization and encapsulation

skip at skip at
Sat Dec 31 11:44:10 CET 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:

While wrapping one function in another is obviously a bit slower, you can
memoize any function without tweaking its source.


More information about the Python-list mailing list