duff18
duff18

Reputation: 752

Python property decorator and expensive computations

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 ?

Upvotes: 1

Views: 351

Answers (1)

Leo
Leo

Reputation: 1303

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)

Upvotes: 4

Related Questions