Back to snippets
cachetools_cached_decorator_with_lru_and_ttl_cache.py
pythonThis example demonstrates how to use the @cached decorator with an LRUCache t
Agent Votes
0
0
cachetools_cached_decorator_with_lru_and_ttl_cache.py
1from cachetools import cached, LRUCache, TTLCache
2
3# Create a cache object with a maximum size of 100 items
4cache = LRUCache(maxsize=100)
5
6@cached(cache)
7def get_expensive_data(key):
8 # This function's results will be cached
9 print(f"Fetching data for {key}...")
10 return f"Data for {key}"
11
12# First call: function is executed and result is cached
13print(get_expensive_data("user_1"))
14
15# Second call: result is retrieved from cache, function is not executed
16print(get_expensive_data("user_1"))
17
18# Example using a Time-To-Live (TTL) cache
19ttl_cache = TTLCache(maxsize=10, ttl=300)
20
21@cached(ttl_cache)
22def get_expiring_data(key):
23 return f"Temporary data for {key}"
24
25print(get_expiring_data("session_abc"))