What is Python's @functools.lru_cache?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
@functools.lru_cache(maxsize=128) is a memoization decorator that caches the results of function calls based on input arguments, returning cached results on subsequent calls with the same arguments. LRU = Least Recently Used — when the cache is full, the least recently used entry is discarded. @lru_cache(maxsize=None) (or @functools.cache in Python 3.9+) has unlimited size. All arguments must be hashable (no lists or dicts). Useful for: recursive algorithms (Fibonacci, factorial — eliminates exponential time complexity), expensive database queries, API calls, and computationally heavy transformations. Check cache stats: func.cache_info() — shows hits, misses, maxsize, currsize. Clear cache: func.cache_clear(). For class methods, use methodtools.lru_cache or use @functools.cached_property for properties.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.