Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple iterator implementing a "back" method
class BackIterator(object):
def __init__(self, iterator):
self.current_index = 0
self.max_index = 0
self.previous_items = []
self.iterator = iterator
def __iter__(self):
return self
def __next__(self):
if self.current_index == self.max_index:
item = next(self.iterator)
self.previous_items.append(item)
self.max_index += 1
else:
item = self.previous_items[self.current_index]
self.current_index += 1
return item
def __back__(self):
if self.current_index < 1:
raise IndexError("Already at beggining of the iterator")
self.current_index -= 1
return self.previous_items[self.current_index]
# for style consistency and Python2 compatibility
next = __next__
back = __back__
@jsbueno

This comment has been minimized.

Copy link
Owner Author

@jsbueno jsbueno commented Mar 18, 2015

Example usage:

>>> bla = Wrapper(open(<arquivo>))
>>> x  = iter(bla)
>>> x.next()
<linha1 do arquivo>
>>> x.next()
<linha2 do arquivo>
>>>x.back()
<linha2 do arquivo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment