Memoization

0.4.0 · active · verified Sat Apr 11

Memoization is a powerful caching library for Python, providing decorators for function memoization with features like Time-To-Live (TTL) expiration, multiple caching algorithms (LRU, LFU, FIFO), and extensibility. It aims to solve some limitations of the standard library's `functools.lru_cache`, such as handling unhashable arguments. The library is actively developed, with its latest release being v0.4.0.

Warnings

Install

Imports

Quickstart

Demonstrates basic memoization with TTL and a quick example of an LRU cache. The `cached` decorator automatically caches the function's return values, avoiding re-computation for the same inputs within the specified TTL or cache size.

import time
from memoization import cached

@cached(ttl=2) # Cache results for 2 seconds
def expensive_calculation(a, b):
    print(f"Calculating {a} + {b}...")
    time.sleep(1) # Simulate a slow operation
    return a + b

print(expensive_calculation(1, 2)) # First call, calculates
print(expensive_calculation(1, 2)) # Second call, uses cache
time.sleep(3) # Wait for cache to expire
print(expensive_calculation(1, 2)) # Cache expired, recalculates

@cached(max_size=2, algorithm='lru')
def lru_example(x):
    print(f"Calculating for {x}...")
    return x * x

lru_example(1)
lru_example(2)
lru_example(3) # 1 will be evicted
lru_example(1) # Re-calculates for 1, 2 is evicted

view raw JSON →