Skip to content

Instantly share code, notes, and snippets.

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.max_index += 1
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__

This comment has been minimized.

Copy link
Owner Author

@jsbueno jsbueno commented Mar 18, 2015

Example usage:

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