Property Cached

1.6.4 · active · verified Thu Apr 16

The `property-cached` library (version 1.6.4) provides a Python decorator to cache the result of a class property's first access. Subsequent accesses to that property on the same instance retrieve the cached value without re-computation. It is a maintained fork of the original `cached-property` library, offering improved compatibility and type hinting support for modern Python versions. Releases are typically driven by bug fixes and compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `cached_property`. The `loaded_data` property will execute its computation only on the first access for a given `MyResource` instance. Subsequent accesses retrieve the cached value. It also shows how to explicitly delete a cached property to force re-computation if the underlying state changes.

from property_cached import cached_property
import time

class MyResource:
    def __init__(self, name):
        self.name = name
        self._heavy_computation_count = 0

    @cached_property
    def loaded_data(self):
        print(f"[{self.name}] Performing heavy computation for data...")
        time.sleep(0.1) # Simulate delay
        self._heavy_computation_count += 1
        return f"Data for {self.name} (computed {self._heavy_computation_count} times)"

resource1 = MyResource("Resource A")
print(f"First access: {resource1.loaded_data}")
print(f"Second access: {resource1.loaded_data}") # Will not re-compute

print("\nModifying resource, then trying to access again...")
# If underlying state changes, the cached property remains stale
resource1.name = "Resource A (modified)"
print(f"Access after name change: {resource1.loaded_data}") # Still uses old cached value

print("\nDeleting cached property to force re-computation...")
del resource1.loaded_data
print(f"Access after deletion: {resource1.loaded_data}") # Re-computes with new name

view raw JSON →