Back to index

plone3  3.1.7
instance.py
Go to the documentation of this file.
00001 """
00002 Memo decorators for instances.
00003 
00004 Stores values in an attribute on the instance. See instance.txt.
00005 
00006 This package current subsumes memojito
00007 """
00008 
00009 _marker = object()
00010 class Memojito(object):
00011     propname = '_memojito_'
00012     def clear(self, inst):
00013         if hasattr(inst, self.propname):
00014             delattr(inst, self.propname)
00015         
00016     def clearbefore(self, func):
00017         def clear(*args, **kwargs):
00018             inst=args[0]
00019             self.clear(inst)
00020             return func(*args, **kwargs)
00021         return clear
00022 
00023     def clearafter(self, func):
00024         def clear(*args, **kwargs):
00025             inst=args[0]
00026             val = func(*args, **kwargs)
00027             self.clear(inst)
00028             return val 
00029         return clear
00030 
00031     def memoize(self, func):
00032         def memogetter(*args, **kwargs):
00033             inst = args[0]
00034             cache = getattr(inst, self.propname, _marker)
00035             if cache is _marker:
00036                 setattr(inst, self.propname, dict())
00037                 cache = getattr(inst, self.propname)
00038 
00039             # XXX this could be potentially big, a custom key should
00040             # be used if the arguments are expected to be big
00041 
00042             key = (func.__name__, args, frozenset(kwargs.items()))
00043             val = cache.get(key, _marker)
00044             if val is _marker:
00045                 val=func(*args, **kwargs)
00046                 cache[key]=val
00047                 setattr(inst, self.propname, cache)
00048             return val
00049         return memogetter
00050 
00051 
00052 _m = Memojito()
00053 memoize = _m.memoize
00054 clearbefore = _m.clearbefore
00055 clearafter = _m.clearafter
00056 
00057 def memoizedproperty(func):
00058     return property(_m.memoize(func))
00059 
00060 __all__ = (memoize, memoizedproperty, clearbefore, clearafter)