I had a bit of a surprise today while going through some Python exercises. I needed to add memoization to a function and I had it all written with custom code. Then I decided to see if there was a more pythony way of solving the problem and I was very surprised by the answer.
One line of code
Okay, technically it is two lines of code if you count the import statement.
from functools import lru_cache [...] @lru_cache(maxsize = 1024) # <-- built-in memoization in one line def my_function(self, x, y): return x + y
Add the lru_cache decorator and your function is wrapped with memoization functionality. You can use maxsize to control how big the cache is – use maxsize=None and the cache is unbounded. Additionally, the decoration provides information about the cache (hits, misses, size). I’m impressed.
Here is the documentation for lru_cache.
As a side note, LRU stands for Least Recently Used.