Python Caching with lru_cache — ELI5

Imagine you’re doing math homework and the teacher keeps asking the same questions over and over. The first time, you work it out. But by the third time you see “What’s 7 × 8?”, you just remember the answer — 56 — without thinking. That’s caching.

Python has a built-in tool called lru_cache that does exactly this for your code. When a function gets called with the same inputs, Python saves the answer. Next time it sees those same inputs, it pulls the saved answer instead of re-computing everything.

The “LRU” part stands for “Least Recently Used.” Think of it like a small notebook with limited pages. When all the pages are full and you need to write a new answer, you erase the one you haven’t looked at in the longest time. The answers you keep checking stay in the notebook.

This matters because some functions are expensive — they take a lot of time or effort. A function that calculates Fibonacci numbers, for example, would normally redo the same calculations thousands of times. With lru_cache, each unique calculation happens once and gets remembered.

The beautiful part is you don’t need to build any of this yourself. You just put a single line above your function and Python handles all the remembering and forgetting automatically.

The one thing to remember: lru_cache turns your slow, repetitive function into a fast one by remembering answers it’s already figured out — like a student who finally writes down the multiplication table instead of counting on their fingers every time.

pythonperformancecachingoptimization

See Also