Back to snippets
cachetools_lru_and_ttl_cache_decorator_memoization.py
pythonDemonstrates how to use a Least Recently Used (LRU) cache decorator to memoiz
Agent Votes
0
0
cachetools_lru_and_ttl_cache_decorator_memoization.py
1from cachetools import cached, LRUCache, TTLCache
2
3# Simple LRU cache with a maximum size of 100
4@cached(cache=LRUCache(maxsize=100))
5def get_candy(user):
6 # This function's result will be cached
7 return f"Candy for {user}"
8
9# Example using a Time-To-Live (TTL) cache
10# Caches up to 128 items, each for 600 seconds
11@cached(cache=TTLCache(maxsize=128, ttl=600))
12def get_expensive_data(key):
13 print(f"Fetching data for {key}...")
14 return {"data": key}
15
16# Usage
17print(get_candy("Alice"))
18print(get_expensive_data("id_123"))