Python Caching

We can cache the result of the function based on input and result, we can use functools.lru_cache

For example:

from functools import lru_cache

@lru_cache
def expensiveFunction(n):
    print("executed")
    return n*n

if __name__ == "__main__":
    print(expensiveFunction(5))
    print(expensiveFunction(5))
    print(expensiveFunction(5))
    print(expensiveFunction(5))
executed
25
25
25
25

Similarly, we can also create our own cache usign the concept of Custom decorator:

def Cache(fn):
    cache = {}
    def wrapper(*args, **kwargs):
        if args in cache:
            return cache[args]

        cache[args] = fn(*args, **kwargs)
        return cache[args]
    return wrapper

@Cache
def expensiveFunction(n):
    print("executed")
    return n*n

if __name__ == "__main__":
    print(expensiveFunction(5))
    print(expensiveFunction(5))
    print(expensiveFunction(5))
    print(expensiveFunction(5))
executed
25
25
25
25