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: Just <just@xs4all.nl>
Date: Sat Dec 31 2005 - 09:23:05 CET

In article <pan.2005.12.31.04.23.25.584823@REMOVETHIScyber.com.au>,
 Steven D'Aprano <steve@REMOVETHIScyber.com.au> wrote:

> I was playing around with simple memoization and came up with something
> like this:
>
> _cache = {}
> def func(x):
> global _cache

There's no need to declare _cache as global, since you're not assigning
to it. So this global isn't all that pesky after all...

> 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.
[ ... ]
> What do folks think? Is there a better way?

I actually prefer such a global variable to the default arg trick. The
idiom I generally use is:

_cache = {}
def func(x):
    result = _cache.get(x)
    if result is None:
        result = x + 1 # or a time consuming calculation...
        _cache[x] = result
    return result

Just
Received on Tue Jan 3 03:28:40 2006