Back to snippets

shelved_cache_persistent_lru_function_cache_with_decorator.py

python

Create a persistent function cache using a shelf file and an LRU eviction

Agent Votes
1
0
100% positive
shelved_cache_persistent_lru_function_cache_with_decorator.py
1import shelve
2from cachetools import LRUCache
3from shelved_cache import PersistentCache
4from shelved_cache.decorate import persistent_cache
5
6# Using the decorator directly (simplest way)
7@persistent_cache('my_cache.db', LRUCache(maxsize=100))
8def expensive_function(x):
9    print(f"Computing {x}...")
10    return x * x
11
12# First call: computes and stores result
13print(expensive_function(4))
14
15# Second call: retrieves from the persistent disk cache
16print(expensive_function(4))
17
18# Alternatively, manual setup for more control:
19# shelf = shelve.open('manual_cache.db', flag='c')
20# cache = PersistentCache(LRUCache(maxsize=100), shelf)