Invalidate a cached Python property when its inputs change
A cached total can stay unchanged after its input values change. Deleting the cached attribute lets the next access calculate it again. Put that invalidation in the same method that replaces the inputs.
Set up
Tested on Linux with CPython 3.12.14. Use Bash, Python 3.12 or newer, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal open and stop if setup fails. Run without -O so the assertions remain enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as cached_total.py:
from functools import cached_property
class Report:
def __init__(self, values):
self.replace_values(values)
def replace_values(self, values):
candidate = tuple(values)
if any(type(value) is not int for value in candidate):
raise ValueError("expected integers")
self.values = candidate
self.__dict__.pop("total", None)
@cached_property
def total(self):
print("Calculating total")
return sum(self.values)
report = Report([2, 3])
print("Initial:", report.total)
report.values = (10, 20)
print("After direct assignment:", report.total)
del report.total
print("After deletion:", report.total)
report.replace_values([7, 8])
print("After replacement:", report.total)
print("Cached read:", report.total)
try:
report.replace_values([1, "bad"])
except ValueError as error:
print("Rejected:", error)
else:
raise AssertionError("expected validation failure")
assert report.values == (7, 8)
assert report.total == 15Run:
python3 -B cached_total.pyObserved output:
Calculating total
Initial: 5
After direct assignment: 5
Calculating total
After deletion: 30
Calculating total
After replacement: 15
Cached read: 15
Rejected: expected integersKeep mutation and invalidation together
The first access stores 5 on the report. Directly assigning new values leaves that stored result in place. Deleting the total makes the next access calculate 30. The replacement method then installs a validated tuple and removes any stored total; the following access calculates 15, and another read reuses it.
Validation finishes before either assignment or invalidation. The rejected string therefore leaves both the previous values and their cached total intact. Converting the input to a tuple also prevents a caller’s later list edits from changing this report’s inputs.
Define the ownership rule
Callers must use the replacement method. This example deliberately exposes a public attribute to demonstrate how bypassing the method produces stale data; it does not enforce encapsulation. A production class can use a validated property setter or make instances effectively immutable. Use an ordinary computed property when recalculation is cheap and mutable inputs are unavoidable.
The method uses __dict__.pop() so invalidation also works before the first cached read. Python’s cached_property documentation explains the instance attribute and deletion behavior. Instances need a mutable __dict__. In Python 3.12 and later, the decorator provides no lock: concurrent reads and input replacement need an explicit synchronization policy. This single-threaded example provides none.
Clean up
Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- cached_total.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.