Backports functools.lru_cache

2.0.0 · active · verified Sat Apr 11

This library provides a backport of the `functools.lru_cache` decorator, originally introduced in Python 3.2, primarily for use in older Python environments (e.g., Python 2.7, 3.2-3.5). For Python versions 3.8 and newer, it acts as a no-op, internally importing the built-in `functools.lru_cache` for compatibility. The current version is 2.0.0, released in December 2023, with updates occurring on an as-needed basis rather than a fixed cadence.

Warnings

Install

Imports

Quickstart

Demonstrates caching an expensive function using the `@lru_cache` decorator. The second call to `expensive_computation(5)` will retrieve the result from the cache, resulting in a much faster execution time.

import time
try:
    from functools import lru_cache
except ImportError:
    from backports.functools_lru_cache import lru_cache

@lru_cache(maxsize=128)
def expensive_computation(n):
    """Simulates an expensive computation."""
    time.sleep(0.1) # Simulate work
    return n * n

print("First call:")
start = time.perf_counter()
result1 = expensive_computation(5)
end = time.perf_counter()
print(f"Result: {result1}, Time taken: {end - start:.4f}s")

print("\nSecond call (should be cached):")
start = time.perf_counter()
result2 = expensive_computation(5)
end = time.perf_counter()
print(f"Result: {result2}, Time taken: {end - start:.4f}s")

print(f"\nCache Info: {expensive_computation.cache_info()}")

view raw JSON →