Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created March 18, 2015 18:06
Show Gist options
  • Save jsbueno/07a3dfad97fc87c4683c to your computer and use it in GitHub Desktop.
Save jsbueno/07a3dfad97fc87c4683c to your computer and use it in GitHub Desktop.
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
Copy link
Author

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