I\'m writing a class in python and I have an attribute that will take a relatively long time to compute, so I only want to do it once. Also, it will not be
With Python 2, but not Python 3, here's what I do. This is about as efficient as you can get:
class X:
@property
def foo(self):
r = 33
self.foo = r
return r
Explanation: Basically, I'm just overloading a property method with the computed value. So after the first time you access the property (for that instance), foo ceases to be a property and becomes an instance attribute. The advantage of this approach is that a cache hit is as cheap as possible because self.__dict__ is being used as the cache, and there is no instance overhead if the property is not used.
This approach doesn't work with Python 3.