CKTIS / Python
Inspect LRU cache statistics with cache_info()
Call `cache_info()` on a decorated function to see its cumulative hits and misses, its configured cache limit, and how many entries it currently holds.
Version: Python 3.12
Syntax
@functools.lru_cache(maxsize=128, typed=False)
def f(net, vat):
...
info = f.cache_info()In Python 3.12, functools.lru_cache wraps a function and stores results based on its arguments, which must be hashable. Call cache_info() on that wrapped function, as in gross_cents.cache_info(), not on the decorator or on the computed result.
The method returns a CacheInfo named tuple: a snapshot of the cache. hits and misses are cumulative counters: a hit reuses a stored result, and a miss means no result was found in the cache. maxsize is the configured entry limit (None means unbounded), and currsize is the current number of entries, not a byte count. Reading the snapshot does not affect the counters. When a bounded cache is full, adding an entry evicts the least recently used entry.
The example caches the result for each item's (net, vat) pair, not the whole basket total. Comparing the two snapshots shows how many results were reused while processing the second basket, but does not tell you how much time was saved.
Examples
from functools import lru_cache
@lru_cache(maxsize=4)
def gross_cents(net, vat):
return net + net * vat // 100
basket_a = [(1000, 20), (500, 10)]
basket_b = [(1000, 20), (200, 5)]
for basket in (basket_a, basket_b):
print(sum(gross_cents(net, vat) for net, vat in basket))
print(gross_cents.cache_info())Result
1750 CacheInfo(hits=0, misses=2, maxsize=4, currsize=2) 1410 CacheInfo(hits=1, misses=3, maxsize=4, currsize=3)
`net` is in cents and `vat` is a whole-number percentage. The first basket causes two misses. The second reuses the result for `(1000, 20)` and adds an entry for `(200, 5)`. Both snapshots come from the same wrapped function.
Related lessons
- Python · Lesson 13 · Advanced · Version: 5