Memoization and encapsulation

Raymond Hettinger python at rcn.com
Sat Dec 31 00:08:29 EST 2005


Steven D'Aprano wrote:
> I was playing around with simple memoization and came up with something
> like this:
>
> _cache = {}
> def func(x):
>     global _cache
>     if _cache.has_key(x):
>         return _cache[x]
>     else:
>         result = x+1  # or a time consuming calculation...
>         _cache[x] = result
>         return result
>
> when it hit me if I could somehow bind the cache to the function, I could
> get rid of that pesky global variable.

Try something like this:

def func(x, _cache={}):
    if x in cache:
        return cache[x]
    result = x + 1 # or a time consuming function
    return result

* If cache hits are the norm, then a try/except version would be a bit
faster.

* In your original code, the global declaration wasn't needed because
the assigment to _cache wasn't changed, rather its contents were.



Raymond




More information about the Python-list mailing list