Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.lru_cache

Caches recent call results while evicting the least recently used key when the size limit is reached.

Version: Python 3.14; repository image, production runtime not attested

Syntax

@functools.lru_cache(maxsize=128, typed=False)

Caches recent call results while evicting the least recently used key when the size limit is reached.

Calling an evicted key computes it again. Cache statistics distinguish a reused entry from a repeated calculation.

Reuse results for hashable argument keys, evicting the least recently used entry at capacity. maxsize=None removes the limit, zero disables storage. typed=True separates immediate argument types. For 1,1,2,1 at capacity one, the second 1 hits and the final 1 misses after eviction, giving one hit and three misses. With typed=False, equal values of different types can still receive separate keys. The cache remains coherent under concurrent access, but overlapping misses may execute the function more than once.

from functools import lru_cache
@lru_cache(maxsize=2, typed=True)
def f(x): return x
assert f(1) == f(1.0) and f.cache_info().currsize == 2
f(1)
f(3)
assert f.cache_info().hits == 1
f(1.0)
assert f.cache_info().misses == 4
@lru_cache(typed=False)
def kind(x): return type(x)
assert kind(1) is int and kind(1.0) is float

lru_cache wrapper.cache_info

cache_info() on the wrapper returns a named tuple. hits counts successful lookups, misses counts misses, maxsize is the configured limit and currsize the current entry count. Eviction can leave currsize below misses.

from functools import lru_cache
@lru_cache(maxsize=2)
def square(n): return n*n
for n in (2,2,3,4): square(n)
info=square.cache_info()
assert (info.hits,info.misses,info.maxsize,info.currsize)==(1,3,2,2)
square.cache_clear()
assert square.cache_info().currsize==0

Examples

import functools
@functools.lru_cache(maxsize=1)
def twice(n): return n * 2

print([twice(n) for n in (1, 1, 2, 1)])
info = twice.cache_info()
print(info.hits, info.misses)

Result

[2, 2, 4, 2]
1 3

Reuse results for hashable argument keys, evicting the least recently used entry at capacity. maxsize=None removes the limit, zero disables storage. typed=True separates immediate argument types. For 1,1,2,1 at capacity one, the second 1 hits and the final 1 misses after eviction, giving one hit and three misses. With typed=False, equal values of different types can still receive separate keys. The cache remains coherent under concurrent access, but overlapping misses may execute the function more than once.

Sources