Use deque maxlen to retain recent status changes
Also published in our Blogger archive.
Use deque maxlen to retain recent status changes
A monitor often receives the same status repeatedly, but an operator usually needs the latest transitions instead of every poll. collections.deque(maxlen=4) provides that bounded history. In this example, record_changes compares each incoming string with current. It appends only a different status, so the deque contains changes in chronological order.
When a fifth change arrives, deque.append automatically discards the oldest item from the opposite end. The printed history therefore retains "degraded", "healthy", "maintenance", and "healthy"; the original "starting" change has aged out. The assertion checks that behavior for this particular input.
A deque does not decide what counts as a meaningful change. Here, spelling and case differences are distinct because the code compares strings exactly. Normalize or validate values before calling the function if that is not desired. Also, a bounded deque is deliberately not an audit log: discarded transitions cannot be recovered, and maxlen must be chosen to fit the amount of recent context the caller needs.
AI assistance was used to draft this article.
from collections import deque
def record_changes(statuses, limit):
history = deque(maxlen=limit)
current = object()
for status in statuses:
if status != current:
history.append(status)
current = status
return history
statuses = ["starting", "starting", "healthy", "degraded", "healthy", "maintenance", "healthy"]
recent = record_changes(statuses, 4)
assert list(recent) == ["degraded", "healthy", "maintenance", "healthy"]
print("recent:", list(recent))
Expected stdout:
recent: ['degraded', 'healthy', 'maintenance', 'healthy']