Created
March 18, 2015 18:06
-
-
Save jsbueno/07a3dfad97fc87c4683c to your computer and use it in GitHub Desktop.
Simple iterator implementing a "back" method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: