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
Python 3.8 includes the functools.cached_property decorator.
Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for the life of the instance. Similar to
property()
, with the addition of caching. Useful for expensive computed properties of instances that are otherwise effectively immutable.
This example is straight from the docs:
from functools import cached_property
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = sequence_of_numbers
@cached_property
def stdev(self):
return statistics.stdev(self._data)
@cached_property
def variance(self):
return statistics.variance(self._data)
The limitation being that the object with the property to be cached must have a __dict__
attribute that is a mutable mapping, ruling out classes with __slots__
unless __dict__
is defined in __slots__
.