Python Cached Method Keeps an Instance Alive: Inspect Cache Ownership
By ON Lab · Sources checked November 9, 2026
A cached method call includes self in its arguments. Inspect the cache’s lifetime and retained keys before assuming del releases the instance.
Reproduce the boundary in a disposable example
Deleting an object does not release it after an lru_cache-decorated method was called.
from functools import lru_cache
import gc, weakref
class Sample:
@lru_cache(maxsize=8)
def double(self, value):
return value * 2
item = Sample()
reference = weakref.ref(item)
assert item.double(3) == 6
assert Sample.double.cache_info().currsize == 1
del item
gc.collect()
assert reference() is not None
Sample.double.cache_clear()
gc.collect()
assert reference() is None
print("method cache retention and release verified")Read the result before changing application code
The weak reference observes lifetime without owning the instance. The cache-size assertion connects that lifetime to a stored call. Clearing the class method’s cache releases this example’s last strong reference, but it also clears entries belonging to every instance using that same decorated function.
Choose the behavior your caller needs
Consider a cached pure helper keyed by the small immutable data actually needed for the calculation. For instance-owned cached state, define a lifetime that matches the instance and test the design, including cycles. A finite maxsize bounds entry count, not the bytes retained by each instance or result. Watch cache_info over a representative workload before deciding the cache saves enough work to justify its memory.
Scope and limits
Local garbage-collection behavior is demonstrated only for this small class. Other references, finalizers and implementation differences can affect release timing. Clearing a cache is a diagnosis here, not a universal memory repair.
Related: compare the adjacent data or execution boundary.
The embedded example was executed in an isolated local Python process on November 9, 2026. It is a reproducible boundary check, not a test of your full application.