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 needed by every instance of the class, so I don't want to do it by default in __init__
.
I'm new to Python, but not to programming. I can come up with a way to do this pretty easily, but I've found over and over again that the 'Pythonic' way of doing something is often much simpler than what I come up with using my experience in other languages.
Is there a 'right' way to do this in Python?
Foo.something_expensive
. All these answers are about cached instance properties, which meanssomething_expensive
will be recalculated for every new instance, which is less than optimal in most cases – Cleodal@classmethod
, which should give you a cached class property. – Micrometeorite@classmethod
and@functools.cached_property
together -- in both orders -- and neither worked. By contrast, the@cachedclassproperty
decorator from the Dickens library did work for me. – Fish