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: Steven D'Aprano <steve@REMOVETHIScyber.com.au>
Date: Sat Dec 31 2005 - 13:19:41 CET

On Fri, 30 Dec 2005 21:08:29 -0800, Raymond Hettinger wrote:

> Steven D'Aprano wrote:
>> I was playing around with simple memoization and came up with something
>> like this:

[snip]

> 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

Of course. The most obvious thing is the least obvious :-)

> * 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.

Sure, it isn't needed, but I still like to make it explicit. Call it a
foible of mine :-)

-- 
Steven
Received on Tue Jan 3 03:28:53 2006