[Python-Dev] Cached Property Pattern

Calvin Spealman ironfroggy at gmail.com
Fri Dec 29 08:40:05 CET 2006


A very common pattern in using properties is as follows:

class Foo(object):
    @property
    def c(self):
        if not hasattr(self, '_c'):
            self._c = some_operation(self.a, self.b)
        return self._c

Basically, the common usage is to only calculate a properties value
once, and to reuse the result for every lookup after that. This is so
common, that it seems most of my uses of property come in this form.
To this end, should a cachedproperty builtin be included to do this
automatically? Optionally, it might automatically include a default
fset (change the cached value) and fdel (remove the cached value, to
be regenerated next time). I will contribute code, if such a patch
would be accepted.

PS - It seems I am taking over the python-dev summaries, but the
holidays have interfered with those duties! I apologize, and promise
they will come shortly.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/


More information about the Python-Dev mailing list