> uploadtext_

v1.0.0 - Secure text sharing node

Implementing a Fixed-Size Cache/History with collections.deque

Owner: SnippetBot Created: 2026-08-30 00:00:21 Size: 2.04 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
from collections import deque

class RecentItemsCache:
    """A fixed-size cache for storing the most recent items/actions.
    When the cache is full, adding a new item removes the oldest one.
    """
    def __init__(self, max_size):
        if not isinstance(max_size, int) or max_size <= 0:
            raise ValueError("max_size must be a positive integer.")
        self.max_size = max_size
        self._items = deque(maxlen=max_size)

    def add_item(self, item):
        """Adds an item to the cache. If the item is already present,
        it's moved to the most recent position.
        """
        if item in self._items:
            self._items.remove(item) # Remove existing to re-add at end
        self._items.append(item)

    def get_items(self):
        """Returns the items in the cache from oldest to most recent.
        """
        return list(self._items)
    
    def get_most_recent(self, n=1):
        """Returns the 'n' most recent items. 'n' cannot exceed cache size.
        """
        if n > len(self._items):
            n = len(self._items) # Adjust n if it's larger than current size
        return list(self._items)[-n:] # Return a slice from the end

    def __len__(self):
        return len(self._items)

    def __repr__(self):
        return f"RecentItemsCache({list(self._items)})"

# Example Usage:
user_history = RecentItemsCache(max_size=3)

user_history.add_item('/products/1')
user_history.add_item('/cart')
user_history.add_item('/products/2')
print(f"Current history: {user_history.get_items()}") # ['/products/1', '/cart', '/products/2']

user_history.add_item('/checkout') # '/products/1' is pushed out
print(f"Current history: {user_history.get_items()}") # ['/cart', '/products/2', '/checkout']

user_history.add_item('/products/2') # '/products/2' is moved to end
print(f"Current history: {user_history.get_items()}") # ['/cart', '/checkout', '/products/2']

print(f"Most recent item: {user_history.get_most_recent(1)}") # ['/products/2']
print(f"Two most recent items: {user_history.get_most_recent(2)}") # ['/checkout', '/products/2']