Python Programming

Function caching is a mechanism to improve the performance by storing the return values of the function. So that each time when they are called with same set of arguments, It will return the value from the cache instead of executing the whole function again. Before Python 3.2 we had to write a custom caching 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.

Implementing function caching in Python 3.2+

from functools import lru_cache

def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print([fibonacci(n) for n in range(10)])

The maxsize argument tells lru_cache about how many recent return values to cache.

We can easily clear the cache by using:


Implementing function caching in Python 2+

Below is a generic way to implement caching in python 2+ versions. There are multiple way to do this caching mechanism.

from functools import wraps

def memoize(function):
    cache = {}
    def wrapper(*args):
        if args in cache:
            return cache[args]
            val = function(*args)
            cache[args] = val
            return val
    return wrapper

def fibonacci(n):
    if n < 2: 
    	return n
    return fibonacci(n - 1) + fibonacci(n - 2)