Cacheout Caching Library
Cacheout is a comprehensive caching library for Python, offering in-memory, dictionary-based caching. It supports various eviction policies including FIFO, LIFO, LRU, MRU, LFU, and RR. Key features include configurable maximum cache size, time-to-live (TTL) expiration per entry, thread-safety, bulk operations, and memoization decorators for functions. The library is actively maintained and is currently at version 0.16.0.
Warnings
- breaking Python 3.6 support was dropped in v0.14.0. Users must upgrade to Python 3.7 or newer to use cacheout >= 0.14.0.
- breaking The `Cache.setup()` method was renamed to `Cache.configure()` in v0.2.0. Direct calls to `setup()` will no longer work.
- breaking The default `Cache.maxsize` changed from 300 to 256 in v0.7.0. If your application relied on the previous default, this might lead to earlier evictions.
- breaking In v0.9.0, `Cache.get_many_by()` and `Cache.delete_many_by()` were removed, and their functionality merged into `Cache.get_many()` and `Cache.delete_many()` respectively.
- breaking In v0.10.0, the behavior of the `default` argument in `Cache.get()` when it's a callable changed. If the key is missing and `default` is a callable, its return value will now be set in the cache for that key.
- gotcha TTL values are in seconds by default, as the default timer function is `time.time`. Be mindful of this unit when setting `ttl` values for caches or individual entries.
Install
-
pip install cacheout
Imports
- Cache
from cacheout import Cache
- CacheManager
from cacheout import CacheManager
- memoize
from cacheout import memoize
- FIFOCache
from cacheout import FIFOCache
Quickstart
from cacheout import Cache
import time
# Initialize a cache with a max size and default TTL (in seconds)
cache = Cache(maxsize=100, ttl=60)
# Set a value
cache.set('key1', 'value1')
# Get a value
print(f"Value for key1: {cache.get('key1')}")
# Set a value with a custom TTL (overriding the default)
cache.set('key2', 'value2', ttl=5)
# Check cache size and keys
print(f"Cache size: {cache.size()}")
print(f"Cache keys: {cache.keys()}")
# Wait for key2 to expire
time.sleep(6)
# Try to get expired key (will return None by default)
print(f"Value for key2 after 6 seconds: {cache.get('key2')}")
# Use a callable default for missing keys (and set it if missing)
print(f"Value for key3 (missing): {cache.get('key3', default=lambda k: f'computed_for_{k}')}")
print(f"Value for key3 (now cached): {cache.get('key3')}")