class SlidingWindow: """Counts events in the last `span` seconds.""" def __init__(self, span): self.span = span self.events = [] def add(self, at): self.events.append(at) def count(self, now): # Keeps events strictly newer than the cutoff. cutoff = now - self.span return len([e for e in self.events if e > cutoff])