OrderedDict move_to_end Reorders Hot Keys

Track most-recently-used keys with OrderedDict: move_to_end on touch, popitem(last=False) evicts from the oldest end, iteration order stays observable.

PythonResilience

Code

pythonsnippet
27 lines
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))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

after warmup  : ['a.conf', 'b.conf', 'c.conf']
after revisit : ['b.conf', 'c.conf', 'a.conf']
evicted: b.conf
after overflow: ['c.conf', 'a.conf', 'd.conf']

How it works

Count the function touch as the entire surface area of OrderedDict move_to_end Reorders Hot Keys.

Using it

The main signature reads def touch(path)

The demo output is labeled (evicted:, after revisit :, after overflow:), so every printed line maps back to its originating operation.

touch is what another module would consume; nothing else here is load-bearing for callers.

Key statements

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)

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `touch` at load time.