SyntaxStudy
Sign Up
Python Memoization with Decorators
Python Intermediate 4 min read

Memoization with Decorators

Memoization

Cache expensive function results with a memoization decorator. Python provides functools.lru_cache out of the box.

Example
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(50))  # instant, no recursion explosion
Pro Tip

Use @functools.cache (Python 3.9+) for an unbounded cache with simpler syntax.