backports.cached_property
`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
- deprecated For Python 3.8 and newer, `functools.cached_property` from the standard library should be used instead. This backport is only necessary for Python 3.6 and 3.7. Using the standard library version is generally preferred for performance and maintainability.
- gotcha The `cached_property` decorator requires that the `__dict__` attribute on each instance be a mutable mapping. This means it will not work with some types, such as metaclasses (where `__dict__` attributes on type instances are read-only proxies for the class namespace) or classes that specify `__slots__` without including `__dict__` as one of the defined slots (as such classes don't provide a `__dict__` attribute at all).
- gotcha `cached_property` values are cached for the life of the instance. If the underlying data that the property depends on changes, the cached property will not automatically re-evaluate. The cached value must be manually cleared by deleting the attribute (e.g., `del instance.property_name`) for it to be recomputed on next access.
Install
-
pip install backports-cached-property
Imports
- cached_property
from backports.cached_property import cached_property
Quickstart
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}")