PYTHON
Building a Simple Fixed-Size In-Memory Cache
Create a basic fixed-size in-memory cache using a standard Python dictionary to store frequently accessed data, managing its capacity manually for web applications.
class SimpleCache:
def __init__(self, max_size: int = 100):
self.max_size = max_size
self._cache = {}
self._keys_order = [] # To track insertion order for basic eviction
def get(self, key):
return self._cache.get(key)
def set(self, key, value):
if key in self._cache:
# Update value and move to end to simulate 'recent' access for basic FIFO/LIFO
self._cache[key] = value
self._keys_order.remove(key)
self._keys_order.append(key)
else:
if len(self._cache) >= self.max_size:
# Evict the oldest item (FIFO-like based on _keys_order)
oldest_key = self._keys_order.pop(0)
del self._cache[oldest_key]
print(f"Cache full. Evicted key: {oldest_key}")
self._cache[key] = value
self._keys_order.append(key)
print(f"Cache updated: {key} = {value}")
def __len__(self):
return len(self._cache)
def __str__(self):
return str(self._cache)
# Example usage for caching API responses or computed results
cache = SimpleCache(max_size=3)
cache.set("user:1", {"name": "Alice", "id": 1})
cache.set("product:101", {"name": "Laptop", "price": 1200})
cache.set("settings:global", {"theme": "dark"})
print(f"
Cache content: {cache}")
# Accessing an item
user = cache.get("user:1")
print(f"
Retrieved user: {user}")
# Add another item, triggering eviction
cache.set("report:daily", {"date": "2023-10-27", "data": "..."})
print(f"
Cache content after eviction: {cache}")
# Accessing an item that was evicted
evicted_user = cache.get("user:1")
print(f"
Retrieved evicted user: {evicted_user}") # Should be None
# Update an existing item (moves it to "more recent" in this simple model)
cache.set("product:101", {"name": "Laptop Pro", "price": 1500})
print(f"
Cache content after update: {cache}")
How it works: This snippet demonstrates building a basic in-memory cache using a standard Python dictionary. It maintains a maximum size and, when full, evicts the "oldest" item (based on insertion order, or re-insertion for updates) to make space for new entries. While not a true LRU cache (which would typically use `collections.OrderedDict`), this manual implementation illustrates managing dictionary size and eviction policies for caching frequently accessed data in scenarios where a simpler, more controlled approach is preferred for web applications.