One-Shot Property?

Daniel Dittmar daniel.dittmar at sap.corp
Tue Jan 18 19:05:37 CET 2005

Kevin Smith wrote:
> I have many cases in my code where I use a property for calculating a 
> value on-demand.  Quite a few of these only need to be called once.  
> After that the value is always the same.  In these properties, I set a 
> variable in the instance as a cached value and return that value on 
> subsequent calls.  It would be nice if there was a descriptor that would 
> do this automatically.  Actually, what would be really nice is if I 
> could replace the property altogether and put the calculated value in 
> its place after the first call, but the property itself prevents me from 
> doing that.  Is this possible?

If you use the old-fashioned __getattr__ method instead of properties. 
__getattr__ gets called only if the value can't be found in the instance 

def __getattr__ (self, attrname):
         method = getattr (self, 'calculate_' + attrname)
     except AttributeError:
         raise AttributeError, attrname
     value = method ()
     setattr (self, attrname, value)
     return value

And probably also through metaclasses. And decorators.


More information about the Python-list mailing list