]> code.communitydata.science - rises_declines_wikia_code.git/blob - mediawiki_dump_tools/Mediawiki-Utilities/mw/util/iteration/peekable.py
add copy of the GPL
[rises_declines_wikia_code.git] / mediawiki_dump_tools / Mediawiki-Utilities / mw / util / iteration / peekable.py
1 def Peekable(it):
2     if isinstance(it, PeekableType):
3         return it
4     else:
5         return PeekableType(it)
6
7
8 class PeekableType:
9     class EMPTY:
10         pass
11
12     def __init__(self, it):
13         self.it = iter(it)
14         self.__cycle()
15
16     def __iter__(self):
17         return self
18
19     def __cycle(self):
20         try:
21             self.lookahead = next(self.it)
22         except StopIteration:
23             self.lookahead = self.EMPTY
24
25     def __next__(self):
26         item = self.peek()
27         self.__cycle()
28         return item
29
30     def peek(self):
31         if self.empty():
32             raise StopIteration()
33         else:
34             return self.lookahead
35
36     def empty(self):
37         return self.lookahead == self.EMPTY

Community Data Science Collective || Want to submit a patch?