实现说明
全部逻辑都在函数 touch中。
使用要点
- 跑完文件,输出里会留下标记——
evicted:、after revisit :、after overflow:。 - 调用方只需要
touch——其余都是内部实现。
常见问题
包管理器会看到什么?
一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 touch。
主要签名是 def touch(path)
核心语句
def touch(path):
# 命中即移到末尾:迭代顺序 = 最近使用顺序
if path in recent:
recent.move_to_end(path)
recent[path] = len(recent)
# 超容量:从最旧的一端弹出 (evict oldest)
if len(recent) > CAPACITY:
evicted, _ = recent.popitem(last=False)
print('evicted:', evicted)
代码示例
from collections import OrderedDict
CAPACITY = 3
recent = OrderedDict()
def touch(path):
# 命中即移到末尾:迭代顺序 = 最近使用顺序
if path in recent:
recent.move_to_end(path)
recent[path] = len(recent)
# 超容量:从最旧的一端弹出 (evict oldest)
if len(recent) > CAPACITY:
evicted, _ = recent.popitem(last=False)
print('evicted:', evicted)
touch('a.conf')
touch('b.conf')
touch('c.conf')
print('after warmup :', list(recent))
touch('a.conf') # 旧条目被重用,重新变成最新
print('after revisit :', list(recent))
touch('d.conf') # 此时最旧的是 b.conf,而不是 a.conf
print('after overflow:', list(recent))