Skip to content

Instantly share code, notes, and snippets.

@dutc
Created June 21, 2014 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dutc/8b2bde9f179edf577f42 to your computer and use it in GitHub Desktop.
Save dutc/8b2bde9f179edf577f42 to your computer and use it in GitHub Desktop.
dinky circular buffer
from collections import deque
class CircularBuffer(deque):
def __init__(self, *args, **kwargs):
self.size = kwargs.pop('size', 3)
super(CircularBuffer, self).__init__(*args, **kwargs)
def append(self, item):
while len(self) >= self.size:
self.popleft()
super(CircularBuffer, self).append(item)
def extend(self, items):
for item in items:
self.append(item)
def appendleft(self, item):
while len(self) >= self.size:
self.pop()
super(CircularBuffer, self).appendleft(item)
def extendleft(self, items):
for item in items:
self.appendleft(item)
if __name__ == '__main__':
notes = 'do re mi fa so la ti'.split()
buf = CircularBuffer()
for note in notes:
print buf
buf.append(note)
buf = CircularBuffer()
for note in notes:
print buf
buf.appendleft(note)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment