Re: Memoization and encapsulation



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

.



Relevant Pages

  • Re: Memoization and encapsulation
    ... > I was playing around with simple memoization and came up with something ... > def func: ... There's no need to declare _cache as global, ...
    (comp.lang.python)
  • Re: Memoization and encapsulation
    ... > I was playing around with simple memoization and came up with something ... > def func: ... > when it hit me if I could somehow bind the cache to the function, ...
    (comp.lang.python)
  • Re: websitedesign.co.uk up for auction
    ... When you are looking for a key phrase and a site that comes up with either some of the words or not all of the words it will say that the words have links to the page using those word/s when you check the cache. ... Yeah, brass, crystal, fancy, Victorian home decor and stuff. ... If you have the stock in inventory why not do both internet marketing and brick and mortar. ...
    (alt.internet.search-engines)
  • Re: websitedesign.co.uk up for auction
    ... and you check the cache it has that the page has links pointing to it for ... that phrase if you don't have the word listed, ... both internet marketing and brick and mortar. ...
    (alt.internet.search-engines)
  • Re: Anyone using an Opteron 165 SK939 as a desktop processor?
    ... from a higher clockspeed than the extra cache. ... the Opteron CPUs (normally way out of price range or on a 940 socket) ... pair of 466 Celerons at 525mhz purely using software tweaks and standard ...
    (uk.comp.homebuilt)