cachetools: Extensible Memoizing Collections and Decorators
Provides various memoizing collections and decorators, including variants of Python's @lru_cache function decorator. Current version: 7.0.5. Release cadence: Regular updates with new features and improvements.
Warnings
- breaking Support for cache(self) returning None to suppress any caching has been deprecated. cache(self) should always return a valid cache object.
- deprecated The typed argument in the cached decorator is deprecated. Use key=typedkey instead.
- gotcha Access to a shared cache from multiple threads must be properly synchronized to avoid concurrency issues.
Install
-
pip install cachetools
Imports
- Cache
from cachetools import Cache
- LRUCache
from cachetools import LRUCache
- cached
from cachetools import cached
Quickstart
import os
from cachetools import cached, LRUCache
# Initialize a cache with a maximum size of 128
cache = LRUCache(maxsize=128)
@cached(cache)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
# Compute the 42nd Fibonacci number
print(fib(42))