How to memoize/cache property access?
Michele Simionato
michele.simionato at gmail.com
Thu Dec 20 11:43:42 EST 2007
On Dec 20, 5:02 pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com>
wrote:
> I seem to be writing the following boilerplate/pattern quite
> frequently to avoid hitting the database until absolutely necessary ...
I use the following module:
$ cat cache.py
class cached(property):
'Convert a method into a cached attribute'
def __init__(self, method):
private = '_' + method.__name__
def fget(s):
try:
return getattr(s, private)
except AttributeError:
value = method(s)
setattr(s, private, value)
return value
def fdel(s):
del s.__dict__[private]
super(cached, self).__init__(fget, fdel=fdel)
@staticmethod
def reset(self):
cls = self.__class__
for name in dir(cls):
attr = getattr(cls, name)
if isinstance(attr, cached):
delattr(self, name)
if __name__ == '__main__': # a simple test
import itertools
counter = itertools.count()
class Test(object):
@cached
def foo(self):
return counter.next()
reset = cached.reset
p = Test()
print p.foo
print p.foo
p.reset()
print p.foo
print p.foo
p.reset()
print p.foo
Michele Simionato
More information about the Python-list
mailing list