backports.cached_property

1.0.2 · maintenance · verified Mon Apr 13

`backports.cached_property` is a Python library that provides a backport of the `functools.cached_property` decorator, which was introduced in Python 3.8. It allows a method of a class to be transformed into a property whose value is computed only once per instance and then cached as a regular attribute. This is particularly useful for expensive computed properties of instances that are otherwise effectively immutable. The current version is 1.0.2, and it appears to be in maintenance mode, as its primary purpose is to backport a feature now in the standard library.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `cached_property` decorator. The `stdev` and `variance` methods are decorated, meaning their values are computed only on the first access and then cached. Subsequent accesses retrieve the cached value without re-executing the method.

import statistics
from backports.cached_property import cached_property

class DataSet:
    def __init__(self, sequence_of_numbers):
        self._data = sequence_of_numbers

    @cached_property
    def stdev(self):
        # This computation will only run once per instance
        print("Calculating standard deviation...")
        return statistics.stdev(self._data)

    @cached_property
    def variance(self):
        # This computation will only run once per instance
        print("Calculating variance...")
        return statistics.variance(self._data)


data = DataSet([1, 2, 3, 4, 5])
print(f"Standard deviation: {data.stdev}")
print(f"Standard deviation (cached): {data.stdev}")
print(f"Variance: {data.variance}")

view raw JSON →