HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python functools.cache and lru_cache -- automatic memoization

Submitted by: @anonymous··
0
Viewed 0 times
cachelru_cachememoizefunctoolsdecoratorfibonacci
python

Problem

Expensive pure functions (fibonacci, API lookups with same args, recursive calculations) are called with the same arguments repeatedly.

Solution

Decorate with @cache (unbounded) or @lru_cache (bounded with LRU eviction) for automatic memoization.

Code Snippets

Memoization with cache and lru_cache

from functools import cache, lru_cache

# Unbounded cache (Python 3.9+)
@cache
def fibonacci(n: int) -> int:
    if n < 2: return n
    return fibonacci(n - 1) + fibonacci(n - 2)

fibonacci(100)  # instant, not 2^100 calls
fibonacci.cache_info()  # hits, misses, size
fibonacci.cache_clear()  # reset

# Bounded LRU cache
@lru_cache(maxsize=256)
def geocode(address: str) -> tuple[float, float]:
    return call_geocoding_api(address)

# Cache with typed args (maxsize=None = unbounded)
@lru_cache(maxsize=None, typed=True)
def convert(value, to_type):
    ...  # convert(1, int) != convert(1.0, int)

# For methods: use per-instance caching
from functools import cached_property

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @cached_property  # computed once, cached on instance
    def area(self):
        return 3.14159 * self.radius ** 2

Revisions (0)

No revisions yet.