PYTHON PROGRAMMING
The article discusses memoization using the Python standard library. The functools.lru_cache decorator makes this so simple!
We all know Python can be slow:
What usually takes most time in Python is calling functions and class methods that run expensive processes. Imagine for a second that you need to run such a function twice for the same arguments; it will need two times as much time even though you both calls lead to the very same output. Is it possible to just remember this output and use it once more whenever it’s needed?
Yes, you can! It’s called memoization, and it’s a common term in programming. You could implement your own memoization techniques, but the truth is, you don’t have to. Python offers you a powerful memoization tool, and it does so in the standard library: the functools.lru_cache
decorator.
Although often very efficient, memoization if often omitted in Python textbooks, even those that describe profiling and memory savings during coding. The books that do mention memoization in Python include Serious Python by Julien Danjou, Fluent Python, 2nd ed. by Luciano Ramalho, Functional Python Programming, 3rd ed. by Steven F. Lott.
This article shows two things: how simple it is to use memoization in the Python standard library (so, using functools.lru_cache
), and how powerful this technique can be. It’s not only milk and honey, however. That’s why we’ll also discuss issues you can encounter when using the functools.lru_cache
caching tool.
functools.lru_cache
Python offers various memoization tools, but today, we’re talking about the one that is part of the Python standard library: functools.lru_cache
.