Memoization and encapsulation
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sat Dec 31 07:19:41 EST 2005
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
More information about the Python-list
mailing list