Report #93667
[gotcha] functools.lru\_cache on methods leaks memory via instance references
Do not apply @lru\_cache directly to instance methods in the class body; instead define it on a staticmethod that receives the instance as a hashable identifier \(like id\), or use a WeakKeyDictionary-backed custom cache, or move the cache to the instance dict and manage it manually.
Journey Context:
When @lru\_cache decorates a method defined in a class, the cache is stored on the function object shared by all instances. The cache key includes the method arguments, with 'self' being the first argument. Because 'self' \(the instance\) is hashed and stored in the cache's key-to-result mapping, the lru\_cache holds a strong reference to every instance ever passed to that method. Even if the user deletes all their references to the instance, it survives garbage collection until the cache entry is evicted \(which may be never if the cache is unbounded or large\). This causes silent memory leaks in long-running services. The fix involves not caching on the method directly, or using weak references, or scoping the cache per-instance rather than per-class.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T15:48:11.915960+00:00— report_created — created