Python 的 lru_cache 淘汰一条缓存后,实例为什么还活着?
用弱引用跟踪 lru_cache 的两次淘汰,观察同一个实例的两个缓存键如何影响实例回收。
给实例方法加上 @lru_cache 后,同一实例可能对应多个缓存键。即使某条记录被淘汰,其他记录仍可通过 self 维持对该实例的引用。用容量为两条的缓存和一个弱引用,就能观察两次淘汰后的对象状态。
同一个实例怎样占用两条缓存
各实例的调用结果由同一方法包装器统一存储。针对 report.render(4) 与 report.render(5),虽实例相同但宽度参数各异,故分别占据一条记录。maxsize=2 限定的是调用记录总量,这意味着单个实例足以填满这两个位置。
用另一个实例逐条淘汰旧记录
首先执行原实例两种宽度的调用,随后利用 weakref.ref(report) 建立弱引用并解除变量绑定。当另一实例首次调用 other.render(1) 时,原实例较早使用的宽度 4 记录被挤出。接着调用 other.render(2) 时,原实例的宽度 5 记录随之被淘汰。这两次调用用的键此前都不在缓存中,期间也没有再次访问旧条目。
import weakref
from functools import lru_cache
class Report:
def __init__(self, label):
self.label = label
@lru_cache(maxsize=2)
def render(self, width):
return self.label[:width]
report = Report("summary")
print("preview:", report.render(4), report.render(5))
ref = weakref.ref(report)
del report
print("after del:", ref() is not None)
other = Report("status")
other.render(1)
print("after one eviction:", ref() is not None)
other.render(2)
print("after two evictions:", ref() is not None)
从弱引用读出实例何时消失
在此独立运行的 CPython 示例中,删除变量后,第一次存活检查输出 True。首次淘汰后结果仍为 True,因为剩余的宽度 5 记录依旧持有该实例。第二次淘汰后则输出 False,此时示例中已无其他强引用。弱引用本身不会延长实例的生命周期。
预期输出
preview: summ summa
after del: True
after one eviction: True
after two evictions: False
排查时确认缓存里还有多少记录
通过 Report.render.cache_info().currsize 可获取当前条目总数。若要判定特定实例是否被缓存持有,还需结合调用参数与访问顺序进行分析。若需在独立排查脚本中清空缓存以作对照,可调用 Report.render.cache_clear(),这将清除整个方法包装器的缓存,涵盖其他实例的记录。如果其他代码仍强引用该实例,清空缓存也不会释放它。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









