1

I normally use @property to avoid situations such as:

def __init__(self, ...):
    self.element = self._getElement()

so that I simply use:

@property
def element(self):
    ...

However this is not very handy when the decorated function performs expensive computations, and if self.element is been called in many parts and different ways, then the computations are performed for every single call.

Is there a way to avoid this, maybe storing the computations results ? Or am I just using @property in the wrong way ?

duff18
  • 358
  • 3
  • 13
  • 1
    some various examples here about memoization: https://stackoverflow.com/questions/1988804/what-is-memoization-and-how-can-i-use-it-in-python – jmunsch Jul 07 '20 at 15:00

1 Answers1

4

The functools module has a built-in decorator to do this. It is called cached_property. Here's an example from the Python 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)