Python - Decorators


Cache

Cache is a way to remember all previous results to a function

from functools import cache
@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

Lru Cache

LRU-Cache (least recently used) is a way to remember the most recent results to a function. Because it does not cache all previous results, it can offer more speed up potential than the cache alternative.

from functools import lru_cache
@lru_cache(maxsize=32)  # Keep track of previous 32 calls
def lru_factorial(n):
    return n * lru_factorial(n-1) if n else 1