In this question (What is the best practice between second assignment or dict's value call?), I first ask for the best solution between second assignment or dict's value call.
But, after few days I realize that the real issue in my problem wasn't really what I asked in the title but instead "How to create a property with cached outputs." My question in the title was about a "wrong" way to solve the problem. A way that should not be, because PEP 20 -- The Zen of Python:
There should be one-- and preferably only one --obvious way to do it.
The good answer corresponding of the question body may be this :
Before 3.8 - functools.lru_cache:
class DataSet:
def __init__(self, sequence_of_numbers):
self._data = sequence_of_numbers
@property
@lru_cache
def stdev(self):
return statistics.stdev(self._data)
@property
@lru_cache
def variance(self):
return statistics.variance(self._data)
Since 3.8 - functools.cached_property:
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.
Example:
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)