Cache Pure Python Lookups with a Bounded lru_cache

A build report may analyze the same diagnostic message hundreds of times. If the analysis depends only on the message text, a small cache can reuse the result. This example caches a sorted vocabulary for each message while keeping the reporting interface free to return a fresh list.

These examples use Python 3.10 or later. The small capacity makes eviction observable; measure a representative workload before choosing a production capacity.

Cache an Immutable Analysis Result

Save this helper as message_vocab.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from functools import lru_cache


@lru_cache(maxsize=2)
def vocabulary(message):
    return tuple(sorted(set(message.casefold().split())))


def vocabulary_list(message):
    return list(vocabulary(message))

The decorated function accepts a hashable string and returns an immutable tuple of strings. It performs simple whitespace tokenization, not punctuation removal or linguistic word segmentation. Its output is deterministic for a given message within the running Python environment.

Save this demonstration beside the helper and run it with Python.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from message_vocab import vocabulary, vocabulary_list

vocabulary.cache_clear()
print(vocabulary("Build OK build"))
print(vocabulary("Build OK build"))
print(vocabulary.cache_info())
# ('build', 'ok')
# ('build', 'ok')
# CacheInfo(hits=1, misses=1, maxsize=2, currsize=1)

words = vocabulary_list("Build OK build")
words.append("local-only")
print(vocabulary_list("Build OK build"))
# ['build', 'ok']

The list wrapper copies the tuple’s references into a new container. Appending to one caller’s list therefore leaves later results intact. Caching a list directly would let callers mutate the value seen by subsequent calls.

Observe Least-Recently-Used Eviction

Run this example in a fresh script beside the helper.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from message_vocab import vocabulary

vocabulary.cache_clear()
for message in ["alpha", "beta", "alpha", "gamma", "beta"]:
    vocabulary(message)
    info = vocabulary.cache_info()
    print(message, info.hits, info.misses, info.currsize)
# alpha 0 1 1
# beta 0 2 2
# alpha 1 2 2
# gamma 1 3 2
# beta 1 4 2

The second access to alpha refreshes its recency. Inserting gamma then evicts beta; the final beta call must recompute. This trace tests reuse without relying on noisy timing measurements.

The cache retains arguments and results until eviction or clearing. Its capacity limits entries, not bytes, and it has no expiration timer. See the API’s ownership, key, and concurrency rules in the Python lru_cache documentation .

Keep the Key Aligned with the Computation

For this helper, the exact input string is the key. "BUILD ok" and "build ok" can occupy separate entries even though the analysis returns equal tuples. Normalizing before the cached boundary could improve reuse, but only if normalization preserves every distinction the computation needs.

Do not add a hidden dependency on a mutable stop-word table or external configuration and expect old entries to update. Pass an immutable version or configuration value into the cached computation, or clear the cache when that dependency changes. Avoid caching an open file, generator, or coroutine as though it were a reusable completed analysis result.

The example uses one positional argument consistently. More elaborate APIs should not assume that reordered keyword arguments or omitted defaults always share cache entries. Lists and dictionaries also cannot be supplied directly as keys to this decorator.

Reset Cache State Deliberately

Call vocabulary.cache_clear() between independent report jobs if retaining earlier message text is unnecessary. Clearing also resets the hit and miss counters, which makes isolated tests predictable. It does not undo lists already returned to callers.

Cache bookkeeping supports concurrent access, but two threads can still compute the same missing key at the same time. This helper tolerates that because the computation has no external effects. A cache is not a mechanism for ensuring that a payment, upload, or other action runs exactly once.

Test Reuse and Result Isolation

Save this as test_message_vocab.py beside the helper and run python test_message_vocab.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from message_vocab import vocabulary, vocabulary_list

vocabulary.cache_clear()
for message in ["alpha", "beta", "alpha", "gamma", "beta"]:
    assert vocabulary(message) == (message,)
info = vocabulary.cache_info()
assert (info.hits, info.misses, info.maxsize, info.currsize) == (1, 4, 2, 2)

vocabulary.cache_clear()
first = vocabulary_list("Build OK build")
second = vocabulary_list("Build OK build")
assert first == second == ["build", "ok"]
assert first is not second
first.clear()
assert vocabulary_list("Build OK build") == ["build", "ok"]
assert vocabulary("") == ()

vocabulary.cache_clear()
info = vocabulary.cache_info()
assert (info.hits, info.misses, info.currsize) == (0, 0, 0)
print("Vocabulary cache checks passed.")

These checks establish the eviction sequence, independent caller lists, empty-input behavior, and reset policy. A separate benchmark should determine whether the saved analysis work exceeds the cost of cache lookups and retained strings for the application’s actual messages.