因为functools.lru_cache仅按访问频次和顺序淘汰、不支持时间过期,且只能缓存函数返回值,无法手动管理键值对;需用OrderedDict+时间戳实现带TTL的LRU字典,确保每次读写都刷新时间戳并维护LRU顺序。

为什么不能直接用 functools.lru_cache 做带过期的字典?
functools.lru_cache 只按调用次数和顺序淘汰,不支持时间过期;它缓存的是函数返回值,不是任意键值对,也没法手动增删查改。你要的是一个“带 TTL 的 LRU 字典”,核心诉求是:键值对在插入/访问时刷新过期时间,容量超限时按最近最少使用 + 过期优先级综合淘汰。
用 collections.OrderedDict 实现 LRU + 时间戳判断
关键思路:把访问时间作为排序依据,每次 __getitem__ 或 __setitem__ 都把对应项移到末尾(move_to_end),定期检查最老项(popitem(last=False))是否过期。注意:不能等取值时才检查过期,否则过期项会卡在内部占用空间。
- 初始化时传入
maxsize和ttl(单位秒),用time.time()记录每个 key 的最后访问时间 - 每次
__setitem__要先检查是否已存在——若存在,需move_to_end并更新时间戳;若不存在且满容,先淘汰最老且过期的项(循环 pop 直到有可用空间或无过期项) - 读取前不做自动清理,但
__contains__和get必须先判断是否过期,过期就del self._data[key]并返回None或抛KeyError - 避免在
__getitem__里直接del后再 raise,会导致for k in cache:迭代异常,应统一由_is_expired判断 +_remove_if_expired清理
__getitem__ 和 __setitem__ 中的时间刷新逻辑怎么写?
必须保证“访问即刷新”:无论是读还是写,只要命中 key,就要更新它的时间戳并移至 OrderedDict 末尾。写操作还要处理新 key 的插入位置和容量控制。
调用 Cutout.Pro 视觉处理 API 进行背景移除、人像抠图和照片增强,支持文件上传与图片 URL 输入。
def __getitem__(self, key):
if not self._is_expired(key):
self._data.move_to_end(key) # 刷新 LRU 顺序
self._access_times[key] = time.time()
return self._data[key]
else:
del self._data[key]
del self._access_times[key]
raise KeyError(key)
<p>def <strong>setitem</strong>(self, key, value):
now = time.time()
if key in self._data:
self._data.move_to_end(key)
elif len(self._data) >= self.maxsize > 0:</p><h1>淘汰:先踢过期项,再踢最老未过期项</h1><pre class='brush:python;toolbar:false;'> while len(self._data) >= self.maxsize and self._data:
oldest_key = next(iter(self._data))
if self._is_expired(oldest_key):
del self._data[oldest_key]
del self._access_times[oldest_key]
else:
break
if len(self._data) >= self.maxsize and self._data:
self._data.popitem(last=False) # 踢最老未过期
oldest_key = next(iter(self._access_times), None)
if oldest_key:
del self._access_times[oldest_key]
self._data[key] = value
self._access_times[key] = now容易被忽略的边界问题:并发、浮点精度、初始 ttl=0
这个类默认非线程安全。如果多线程写,move_to_end 和 popitem 可能引发 RuntimeError: dictionary changed size during iteration。真要并发,得加 threading.RLock 包裹所有修改操作。
立即学习“Python免费学习笔记(深入)”;
-
time.time()返回 float,高并发下可能撞时间戳,但不影响正确性,只影响淘汰顺序精度 -
ttl=0应视为“永不过期”,但代码里要显式判断if self.ttl ,否则 <code>now - access_time > 0总为真 -
maxsize=None或0表示不限容量,此时淘汰逻辑要跳过,否则len(self._data) >= 0永真 - 清空操作
clear()必须同步清理_access_times,否则残留时间戳会导致后续误判过期
真正难的不是结构,而是把“过期”和“LRU顺序”两个维度在每次操作中无遗漏地耦合起来——漏一次 move_to_end,LRU 就乱;少一次 del,内存就悄悄涨。

















