Re: Memoization and encapsulation
- From: Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 31 Dec 2005 23:19:41 +1100
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
.
- References:
- Memoization and encapsulation
- From: Steven D'Aprano
- Re: Memoization and encapsulation
- From: Raymond Hettinger
- Memoization and encapsulation
- Prev by Date: Re: py-cocoa?
- Next by Date: Re: Memoization and encapsulation
- Previous by thread: Re: Memoization and encapsulation
- Next by thread: Re: Memoization and encapsulation
- Index(es):
Relevant Pages
|