[Zope-CMF] Re: RFC: browser views and memoization

yuppie y.2006_ at wcm-solutions.de
Mon Jan 16 07:15:20 EST 2006


yuppie wrote:
> whit wrote:
>> yuppie wrote:
>>>
>>> I ended up using this method as decorator for most methods:
>>>
>>> def memoize(func):
>>>     memo = {}
>>>     def memoized_func(*args):
>>>         if args not in memo:
>>>             memo[args] = func(*args)
>>>         return memo[args]
>>>     return memoized_func
>>>
>>>
>>> Are there better ways to resolve this?
>>>
>>> Will those memo dicts be removed together with the view object or 
>>> does this create a potential memory leak? (I'm not very familiar with 
>>> decorators.)
>>
>> that's pretty elegant compared to shoving a multitude of values into 
>> the view.  The closest thing to it would be a PEAK binding, but even 
>> that can't handle the variety of situations that keing the memo by 
>> function signature gives you. very nice.
> 
> Besides the fact it doesn't work :(
> 
>> that looks safe; as far as I can tell when the decorated method is 
>> garbage collected with the view, all refs to 'memo' should be reaped..
> 
> Digging a bit deeper it looks like decoraters are created on class 
> level, not on instance level. So 'memo' is not garbage collected with 
> the view, it's the same for all instances and grows with each request. 
> That's not exactly the behavior I want.
> 
> Have to think about it a bit more. Any input is welcome.

Ok. This *seems* to work:

def memoize(meth):
     def memoized_meth(self, *args):
         if not hasattr(self, '_memo'):
             self._memo = {}
         sig = (meth, args)
         if sig not in self._memo:
             self._memo[sig] = meth(self, *args)
         return self._memo[sig]
     return memoized_meth

_memo is now an instance attribute and should be garbage collected with 
the view instance. Does that look sane?

I don't care about kwargs and non-hashable args at the moment. I just 
want to find out if using a memoize decorator is the right approach for 
resolving the problem described in my initial mail.


Cheers, Yuppie



More information about the Zope-CMF mailing list