Functools LRU Cache Maxsize Tuning

Accelerate pure lookups with functools.lru_cache, sizing maxsize from hit rates and isolating unhashable arguments.

PythonData Fetching

Code

pythonsnippet
48 lines
import functools
import time


def load_catalog():
    return {f'SKU-{i}': {'price': i * 3, 'stock': i % 7} for i in range(500)}


CATALOG = load_catalog()


@functools.lru_cache(maxsize=256)
def price_of(sku: str) -> int:
    # 纯查表函数:缓存命中即免重复计算
    return CATALOG[sku]['price']


@functools.lru_cache(maxsize=64)
def bundle_price(skus: tuple[str, ...]) -> int:
    # 参数必须是可哈希的:列表要转元组
    return sum(price_of(s) for s in skus)


def cache_report():
    info = price_of.cache_info()
    total = info.hits + info.misses
    hit_rate = info.hits / total if total else 0.0
    return {
        'hit_rate': round(hit_rate, 3),
        'hits': info.hits,
        'misses': info.misses,
        'maxsize': info.maxsize,
        'currsize': info.currsize,
    }


skus = [f'SKU-{i}' for i in range(60)]
start = time.perf_counter()
for _ in range(3):
    for sku in skus:
        price_of(sku)
elapsed = time.perf_counter() - start

print(cache_report())
print(f'60 keys x 3 rounds in {elapsed * 1000:.1f}ms')

# 命中率下降说明工作集超过 maxsize:调大或按业务键分布重新评估
price_of.cache_clear()

Output

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

{'hit_rate': 0.667, 'hits': 120, 'misses': 60, 'maxsize': 256, 'currsize': 60}
60 keys x 3 rounds in 0.0ms

How it works

Count the functions load_catalog, price_of, bundle_price and cache_report as the entire surface area of Functools LRU Cache Maxsize Tuning.

Iteration happens inside for _ in range(3) — everything outside it runs once.

The return value is newly constructed — inputs are never handed back.

Putting it to use

The main signature reads def load_catalog()

The demo output is labeled (60 keys x 3 rounds in), so every printed line maps back to its originating operation.

Import load_catalog from the file and call it — the rest of the code is implementation detail.

Core lines

return {f'SKU-{i}': {'price': i * 3, 'stock': i % 7} for i in range(500)}
def bundle_price(skus: tuple[str, ...]) -> int:
    # 参数必须是可哈希的:列表要转元组
    return sum(price_of(s) for s in skus)
return sum(price_of(s) for s in skus)
def cache_report():
info = price_of.cache_info()
total = info.hits + info.misses
hit_rate = info.hits / total if total else 0.0
return {
'hit_rate': round(hit_rate, 3),
'hits': info.hits,
'misses': info.misses,
'maxsize': info.maxsize,
'currsize': info.currsize,
}

Interactive Tools for This Topic

FAQ

Does `load_catalog` modify its input?
No mutation happens — the function reads its input and returns a new value.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `load_catalog`, `price_of`, `bundle_price` at load time.