[Python-Dev] RFC: readproperty

Jim Fulton jim at zope.com
Wed Sep 28 16:16:12 CEST 2005

Read descriptors (defining only __get__) and data descripttors have
(defining __get__ and __set__) different semantics. In particular,
read descriptors are overridden by instance data, while data
descriptors are not.  A common use of read descriptors is for lazily
computed data:

   class readproperty(object):
       "Create a read descriptor from a function"

       def __init__(self, func):
           self.func = func

       def __get__(self, inst, class_):
           if inst is None:
               return self

           return self.func(inst)

   class Spam:

       def eggs(self):
           ... expensive computation of eggs

           self.eggs = result
           return result

When we ask for the eggs attribute the first time, we call the
descriptor, which calls the eggs function.  The function sets the eggs
attribute, overriding the descriptor. The next time the eggs attribute
is accessed, the saved value will be used without calling the

I do this often enough that I think it would be useful to include it
in python, either as a builtin (like property) or in the library.  (Or
possibly by adding an option to property to generate a read
descriptor.) I'd be happy to add this for 2.5.



Jim Fulton           mailto:jim at zope.com       Python Powered!
CTO                  (540) 361-1714            http://www.python.org
Zope Corporation     http://www.zope.com       http://www.zope.org

More information about the Python-Dev mailing list