Re: Memoization and encapsulation



Steven D'Aprano wrote:
> 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.

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

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



Raymond

.



Relevant Pages

  • Re: Memoization, files and Marshal?
    ... I changed the code to save it once every N misses, and made the cache update atomic to prevent problems with: ... end include Memoize module DumbFib def fibreturn n if n < 2 ...
    (comp.lang.ruby)
  • Re: WeakRef Hash
    ... > class WeakCache ... > def initialize(cache = Hash.new) ...
    (comp.lang.ruby)
  • Re: Bizarre behavior with mutable default arguments
    ... The caller might want to provide it's own pre-prepared cache. ... def foo: ... Global variables are rightly Considered Harmful. ...
    (comp.lang.python)
  • Re: memoize to a file
    ... I've made a file caching example using PSTore for my toy Memoizable library. ... This cache uses PStore to provide ... def initialize(path) ... def memoize(name, cache = Hash.new) ...
    (comp.lang.ruby)
  • 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)