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

whit whit at burningman.com
Mon Jan 16 00:30:49 EST 2006


yuppie wrote:
> Hi!
> 
> 
> The skin scripts for complex forms in CMF like folder_contents are 
> currently big monolithic blocks of code. All the values needed in the 
> template are computed in a predefined order that makes sure expensive 
> tasks like querying the catalog or listing folder contents are performed 
> only once (per request).
> 
> Trying to convert this into a browser view and to split the code in 
> several methods I stumbled other the following issue:
> 
> If globally needed values are returned by their own method they have to 
> be computed again and again, although during the short live of a view 
> class they can be considered static.
> 
> One option would be to pre-compute those values in the __call__ method 
> and to store them in the view object. An other option is to cache the 
> results.
> 
> 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.

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..

In python 2.4 you could use frozenset to have keyword support too.  I 
think something like this would work:

 > def memoize(func):
 >     memo = {}
 >     def memoized_func(*args, **kwargs):
 >         sig = (args, frozenset(kwargs.items()))
 >         if sig not in memo:
 >             memo[sig] = func(*args, **kwargs)
 >         return memo[sig]
 >     return memoized_func


-w



More information about the Zope-CMF mailing list