ID EN
Functools

cached_property

Python 3.11

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.

Syntax

PYTHON
@functools.cached_property(func)

Examples

Example 1
PYTHON
class DataSet:

    def __init__(self, sequence_of_numbers):
        self._data = tuple(sequence_of_numbers)

    @cached_property
    def stdev(self):
        return statistics.stdev(self._data)

See Also

property() cached_property() property() cached_property() property() lru_cache() How do I cache method calls? cached_property()