conditional computation
robert
no-spam at no-spam-no-spam.com
Fri Oct 27 10:02:16 EDT 2006
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()"), stores it to the cache dict and the value is returned.
then on cache hit the stored value is just returned from the cache dict "try: return self[k]" and the lambda is not executed again.
note: the lambda expression expensive-calc-expr is just compiled but not executed as long as it is not called ( "f()" )
-robert
More information about the Python-list
mailing list