conditional computation

Fredrik Lundh fredrik at pythonware.com
Thu Oct 26 22:20:25 CEST 2006


robert wrote:

> I want to use a computation cache scheme like
> 
> 	o = CACHECOMPUTE  complex-key-expr  expensive-calc-expr 
> 
> frequently and elegantly without writing complex-key-expr or expensive-calc-expr twice.
> So its ugly:
> 
> 	_=complex-key-expr; o=cache.get(_) or cache.setdefault(_,expensive-calc-expr)
> 
> Any ideas?

in Python 2.5:

     cache = collections.defaultdict(lambda: expensive-calc-expr)
     value = cache[complex-key-expr]

or, if expensive-calc-expr needs access to the key:

     class mycache(dict):
         def __missing__(self, key):
             value = expensive-calc-expr(key)
             self[key] = value
             return value

     cache = mycache()
     value = cache[complex-key-expr]

or, if expensive-calc-expr needs access to more than just the key, or 
you need to run this on more than just 2.5:

     cache = {}

     key = complex-key-expr
     try:
         value = cache[key]
     except KeyError:
         value = cache[key] = expensive-calc-expr

</F>




More information about the Python-list mailing list