Re: Memoization and encapsulation
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Memoization and encapsulation

From: Raymond Hettinger <python@rcn.com>
Date: Sat Dec 31 2005 - 06:08:29 CET

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
Received on Tue Jan 3 03:28:33 2006