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?

I was going to recommend taking a look at the "memoize" example on the Python wiki, but it seems to be missing at the moment. In any case, here's the URL:


http://www.python.org/moin/PythonDecoratorLibrary

There are also a few examples on the Cookbook, like this one:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205

It shouldn't be too difficult to adapt this technique so that it can be used to create properties. I wouldn't bother replacing the property with an attribute unless you have a specific reason to do so (performance, perhaps).

HTH,
Dave
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to