PYTHON

Implement a Fixed-Size Cache with deque

Learn how to create an efficient fixed-size cache or history buffer in Python using collections.deque, ideal for recent items or limited-memory logging.

from collections import deque

class FixedSizeCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = deque(maxlen=capacity)

    def add(self, item):
        # If item is already in cache, remove it to re-add at front (LRU behavior)
        if item in self.cache:
            self.cache.remove(item)
        self.cache.appendleft(item) # Add to the front

    def get_all(self):
        return list(self.cache)

    def __repr__(self):
        return f"FixedSizeCache(capacity={self.capacity}, items={list(self.cache)})"

# Example usage in a web context (e.g., recent user actions)
user_activity_log = FixedSizeCache(capacity=3)
user_activity_log.add("view_product_A")
user_activity_log.add("add_to_cart_A")
user_activity_log.add("view_product_B")
print(user_activity_log.get_all()) # Output: ['view_product_B', 'add_to_cart_A', 'view_product_A']

user_activity_log.add("view_product_A") # A is now most recent
print(user_activity_log.get_all()) # Output: ['view_product_A', 'view_product_B', 'add_to_cart_A']

user_activity_log.add("checkout") # B will be pushed out
print(user_activity_log.get_all()) # Output: ['checkout', 'view_product_A', 'view_product_B']
How it works: The `collections.deque` (double-ended queue) is used here to create a fixed-size cache. When `maxlen` is specified, the deque automatically discards elements from the opposite end when new items are added. This snippet demonstrates a Last Recently Used (LRU) like behavior by removing an item if it exists before adding it to the front, ensuring recently accessed items stay in the cache.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs