Function caching
Allows us to cache the return values of a function depending on the arguments.
It can save time when an I/O bound function is periodically called with the same arguments.
Before Python 3.2 we had to write a custom implementation. In Python 3.2+ there is an lru_cache
decorator which allows us to quickly cache and uncache the return values of a function.
Python 3.2+
Example: Fibonacci calculator with lru_cache
.
The maxsize
argument tells lru_cache
about how many recent return values to cache.
We can uncache the return values:
Python 2+
There are a couple of ways to achieve the same effect. You can create any type of caching mechanism. It entirely depends upon your needs. Here is a generic cache:
Note: memoize won’t cache unhashable types (dict, lists, etc…) but only the immutable types. Keep that in mind when using it.
Further reading
Last updated