conditional computation
robert
no-spam at no-spam-no-spam.com
Thu Oct 26 16:18:08 EDT 2006
Gabriel Genellina wrote:
> At Thursday 26/10/2006 16:30, 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?
>
> The memoize pattern can help; in
> http://wiki.python.org/moin/PythonDecoratorLibrary you can see an
> implementation using decorators.
>
thanks, as such it will not help hooking single line expressions, but it helped me remember the lambda ! :shame: :
class MemoCache(dict): # cache expensive Objects during a session (memory only)
def memo(self, k, f):
try: return self[k]
except IndexError:
return self.setdefault(k, f())
cache=MemoCache()
...
o = cache.memo( complex-key-expr, lambda: expensive-calc-expr )
Thats pythonic now.
-robert
More information about the Python-list
mailing list