Registry / backports-cached-property

backports-cached-property

JSON →
library1.0.2pypypi✓ verified 22d ago

`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.

pip install backports-cached-property
INSTALL
IMPORT
SIG · BACKPORTS-CACHED-P
B
backports-cached-property
pythonv1.0.2
Install
1.5s avg
Import
17ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.0.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.018s · 17.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.5s · import 0.016s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cached_property
from backports.cached_property import cached_property

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}")
Debug
Known issues
deprecatedFor 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.
fix
If running on Python 3.8 or higher, change `from backports.cached_property import cached_property` to `from functools import cached_property`.
affects: <3.8 (if using this backport for >=3.8)
gotchaThe `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).
fix
Avoid using `cached_property` on metaclasses or classes that use `__slots__` without explicitly including `__dict__` in the `__slots__` definition.
affects: All versions
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.
fix
If the state relevant to a cached property changes, explicitly `del` the cached attribute to force re-evaluation on the next access.
affects: All versions
Errors
Common errors & fixes
ImportError: cannot import name 'cached_property' from 'functools'
This error occurs when attempting to import `cached_property` from the `functools` module on Python versions older than 3.8, as `functools.cached_property` was introduced in Python 3.8.
fix
For Python 3.6 and 3.7, you need to install the `backports.cached_property` library and import it from there.

```python
# First, install the backport library
# pip install backports.cached_property

# Then, import from the backport
from backports.cached_property import cached_property
```
ModuleNotFoundError: No module named 'backports.cached_property'
This error indicates that the `backports.cached_property` library has not been installed in your Python environment.
fix
You need to install the library using pip.

```bash
pip install backports.cached_property
```
AttributeError: 'cached_property' object has no attribute 'setter' OR cached_property not working with __slots__
`cached_property` is designed for immutable values and does not support defining a setter like a regular `@property`. Additionally, it requires instances to have a mutable `__dict__` attribute to store the cached value, meaning it will not work with classes that use `__slots__` without explicitly including `__dict__` in the slots.
fix
If you need a mutable property, use the standard `@property` decorator with a `@property.setter`. If using `__slots__`, either avoid `cached_property` or ensure `__dict__` is included in `__slots__` if you absolutely need to use `cached_property` with slotted classes. To clear a cached value, `del instance.property_name` to force re-evaluation on next access.

```python
# Example for setter
class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def my_property(self):
        return self._value

    @my_property.setter
    def my_property(self, new_value):
        self._value = new_value

# Example for __slots__ (avoiding cached_property or including __dict__)
class SlottedClassWithDict:
    __slots__ = ('_data', '__dict__') # Include __dict__ explicitly
    def __init__(self, data):
        self._data = data

    from backports.cached_property import cached_property
    @cached_property
    def computed_value(self):
        print("Computing value...")
        return self._data * 2
```
Warning: 'backports.cached_property' is deprecated (or similar message when using on Python 3.8+)
The `backports.cached_property` library is a backport for Python versions older than 3.8. On Python 3.8 and newer, the native `functools.cached_property` is available in the standard library and is generally preferred for performance and maintainability, leading to warnings or recommendations to switch.
fix
If you are running Python 3.8 or a newer version, you should switch your import statement to use the standard library version.

```python
# Change this:
# from backports.cached_property import cached_property

# To this for Python 3.8+:
from functools import cached_property
```
Upgrade
Version history
1.0.2latest on PyPI · released Jun 14, 2022
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Resources
backports-cached-property — pip install backports-cached-property · libregistry