[Python-ideas] caching properties

gagsl-py2 at yahoo.com.ar gagsl-py2 at yahoo.com.ar
Fri May 1 03:42:20 CEST 2009


En Thu, 30 Apr 2009 17:59:55 -0300, Jared Grubb escribió:

> The only thing I dislike is how many dictionary lookups are required in
> order to return the value after it's been cached. I count 4 lookups
> (object.prop, prop.__call__, self._cache, and self._cache[args]). These
> add up, especially if object.prop could have returned the value
> immediately without having to go through so much indirection (but this
> is not currently possible)

It is not possible if one insist on using property. But Oleg Broytmann's
CachedAttribute class works fine -- it seems to me it didn't get the
deserved attention. I'll repost a slightly modified version:

class CachedAttribute(object):
 
         def __init__(self, method, name=None):
             self.method = method
             self.name = name or method.__name__
             self.__doc__  = method.__doc__
 
         def __get__(self, inst, cls):
             if inst is None:
                 return self
             result = self.method(inst)
             setattr(inst, self.name, result)
             return result
 
class Foo(object):
 
         @CachedAttribute
         def expensive(self):
             "docstring for the expensive property"
             print("computing value...")
             return 42
 
py> f = Foo()
py> f.expensive
computing value...
42
py> f.expensive
42
py> f.expensive = 43
py> f.expensive
43
py> del f.expensive
py> f.expensive
computing value...
42
py> f.expensive
42
py>
 
Note that once the value is computed, it becomes an instance attribute;
later accesses retrieve it directly, no indirection is involved.
 
--
Gabriel Genellina


      Yahoo! Cocina
Recetas prácticas y comida saludable
http://ar.mujer.yahoo.com/cocina/



More information about the Python-ideas mailing list