PYTHON
Implement Fixed-Size History/Log with `collections.deque`
Create efficient, fixed-length queues or history buffers in Python using `collections.deque`, perfect for storing recent user actions or log entries in web applications.
from collections import deque
# Create a deque with a maximum length of 5
recent_actions = deque(maxlen=5)
def log_action(user_id, action):
recent_actions.append(f"User {user_id}: {action}")
print(f"Current recent actions: {list(recent_actions)}")
log_action(101, "logged in")
log_action(102, "viewed profile")
log_action(101, "edited settings")
log_action(103, "posted comment")
log_action(102, "logged out")
log_action(104, "registered new account") # This will push out the oldest action
print(f"Final 5 recent actions: {list(recent_actions)}")
# Example: Storing last N error messages
error_buffer = deque(maxlen=3)
error_buffer.append("DB connection failed")
error_buffer.append("Auth token expired")
error_buffer.append("Invalid API key")
error_buffer.append("Service unavailable") # 'DB connection failed' is removed
print(f"Last 3 errors: {list(error_buffer)}")
How it works: This snippet demonstrates `collections.deque` (double-ended queue) configured with a `maxlen` argument. When the deque reaches its maximum length, adding new elements automatically removes elements from the opposite end, making it perfect for implementing fixed-size history buffers, activity logs, or storing the last 'N' items in a web application context without manual truncation. It offers O(1) performance for appends and pops from both ends, making it highly efficient.