What is Python's @functools.lru_cache?
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.