Memoization and encapsulation



I was playing around with simple memoization and came up with something
like this:

_cache = {}
def func(x):
global _cache
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.

I tried this:

>>> def func(x):
.... try:
.... func.cache
.... except AttributeError:
.... func.cache = {}
.... if func.cache.has_key(x):
.... return func.cache[x]
.... else:
.... result = x + 1
.... func.cache[x] = result
.... return result

and it works as expected, but it lacks elegance.

Instead of using a function, I can also use a new-style class as if it
were a function:

>>> class Func(object):
.... cache = {}
.... def __new__(self, x):
.... if self.cache.has_key(x):
.... return self.cache[x]
.... else:
.... result = x+1
.... self.cache[x] = result
.... return result

and again it works, but I can't help feeling it is an abuse of the class
mechanism to do this.

What do folks think? Is there a better way?



--
Steven.

.



Relevant Pages

  • Re: DIRCACHE hit rate.
    ... if these hit rates would improve simply by upgrading. ... I have work extensively with disk cache tuning over the past 25 years. ... header higher than index. ...
    (comp.os.vms)
  • Re: performance issues
    ... >reformatting twice, ... >running that has not dumped memory and released cache (or ... This is often DEL, and if you hit ... sure that CPU Level 1 Cache and CPU Level 2 Cache are enabled. ...
    (microsoft.public.windowsxp.general)
  • Re: [Info-Ingres] [openroad-users] Performance problems when table page size increased from
    ... Get your DBA to run a tracepoint DM420 to see how each cache is performing. ... I try to aim for>95% cache hit ratio but with very large table scans it is ... You will get a better response to Ingres DBA type questions at the community ...
    (comp.databases.ingres)
  • Re: cache not a ROM, inferring, xilinx
    ... entity cachee is ... TYPE eachCache IS ARRAY OF entry; ... VARIABLE hit: BOOLEAN; ... --write data in cache and memory ...
    (comp.lang.vhdl)
  • Re: Embedded DRAM
    ... bit blocks) stride would hit the same bank on every access, ... Other than the repetative hit is at 4096 byte strides, ... of SRAM as cache and no back to back penalty. ... nobody ever swaps it out for the 4X-6X DRAM version. ...
    (comp.arch)