Functools Cache Memoization Tradeoffs

Memoize pure functions with lru_cache and cache, inspect hit statistics, and cap memory with maxsize for unbounded argument spaces.

PythonData Integrity

Code

pythonsnippet
23 lines
from functools import cache, lru_cache


@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


@cache  # maxsize=None:适合参数空间有限的纯函数
def parse_header(raw: str) -> tuple:
    return tuple(part.strip() for part in raw.split(','))


if __name__ == '__main__':
    print([fibonacci(i) for i in range(10)])
    print('cache info:', fibonacci.cache_info())
    # hits/misses 展示记忆化收益;maxsize=128 上限防止参数空间爆炸

    parse_header('a, b, c')
    parse_header('a,  b ,c')  # 相同规范化结果命中缓存
    print('header cache:', parse_header.cache_info())

Output

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

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
cache info: CacheInfo(hits=16, misses=10, maxsize=128, currsize=10)
header cache: CacheInfo(hits=0, misses=2, maxsize=None, currsize=2)

How the snippet works

Functools Cache Memoization Tradeoffs keeps everything in the functions fibonacci and parse_header.

Applying it

Entry signature: def fibonacci(n: int) -> int

Output lines are prefixed (cache info:, header cache:), making each step’s effect easy to spot.

Statements that matter

def parse_header(raw: str) -> tuple:
    return tuple(part.strip() for part in raw.split(','))
def fibonacci(n: int) -> int:
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

Interactive Tools for This Topic

FAQ

What does Functools Cache Memoization Tradeoffs print when run?
No setup needed: run the file and look for labeled lines like `cache info:`, `header cache:` in the output.