Back to index

plone3  3.1.7
memoize.py
Go to the documentation of this file.
00001 """
00002 Memoize decorator for methods whose first argument is the request.
00003 
00004 Stores values in an annotation of the request.
00005 
00006 This is based on ViewMemo from plone.memoize.
00007 """
00008 
00009 from zope.annotation.interfaces import IAnnotations
00010 
00011 _marker = object()
00012 class PTSMemo(object):
00013     
00014     key = 'pts.memoize'
00015     
00016     def memoize(self, func):
00017         def memogetter(*args, **kwargs):
00018             instance = args[0]
00019             request = args[1]
00020             
00021             annotations = IAnnotations(request)
00022             cache = annotations.get(self.key, _marker)
00023             
00024             if cache is _marker:
00025                 cache = annotations[self.key] = dict()
00026             
00027             key = hash((instance.__class__.__name__, func.__name__, 
00028                         args[1:], frozenset(kwargs.items())),)
00029             value = cache.get(key, _marker)
00030             if value is _marker:
00031                 value = cache[key] = func(*args, **kwargs)
00032             return value
00033         return memogetter
00034 
00035 _m = PTSMemo()
00036 memoize = _m.memoize
00037 
00038 class NegotiatorMemo(object):
00039     
00040     key = 'pts.memoize_second'
00041     
00042     def memoize(self, func):
00043         def memogetter(*args):
00044             instance = args[0]
00045             request = args[2]
00046             
00047             annotations = IAnnotations(request)
00048             cache = annotations.get(self.key, _marker)
00049             
00050             if cache is _marker:
00051                 cache = annotations[self.key] = dict()
00052             
00053             key = hash((instance.__class__.__name__, func.__name__),)
00054             value = cache.get(key, _marker)
00055             if value is _marker:
00056                 value = cache[key] = func(*args)
00057             return value
00058         return memogetter
00059 
00060 _n = NegotiatorMemo()
00061 memoize_second = _n.memoize
00062 
00063 __all__ = (memoize, memoize_second, )