conditional computation

Bruno Desthuilliers onurb at xiludom.gro
Fri Oct 27 17:33:10 CEST 2006


robert wrote:
> Bruno Desthuilliers wrote:
>> robert wrote:
>>> Bruno Desthuilliers wrote:
>>>> robert a écrit :
>>>> (snip)
>>>>> class MemoCache(dict): # cache expensive Objects during a session
>>>>> (memory only)
>>>>>    def memo(self, k, f):
>>>>>        try: return self[k]
>>>>>        except KeyError:            #<--------- was error          
>>>>>             return self.setdefault(k, f())
>>>>> cache=MemoCache()
>>>>> ...
>>>>>
>>>>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )
>>>>>
>>>> And how do you get back the cached value without rewriting both
>>>> complex-key-expr *and* expensive-calc-expr ? Or did I missed the
>>>> point ?
>>> the complex-key-expr is written only once in the code
>>
>> How do you get something back from the cache then ?
>>
>>> expensive-calc-expr is  written only once in code 
>>
>> Same problem here...  I fail to understand how you intend to use this
>> "cache".
> 
> the first time, "self.setdefault(k, f())" executes the lambda ("f()"),
(snip)
Robert, that's not the point. I do have enough Python knowledge to
understand this (totally trivial) code !-)

What I don't understand is how this code is supposed to save you from
having to actually write both complex-key-expr and
expensive-calc-expression more than once. You need them both each time
you access the cache - whether the result of expensive-calc-expression
has already been cached or not.

Now this seems so obvious that I guess I failed to understand some point
in your original spec (emphasis is mine):
"""
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*.
"""


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list