| OLD | NEW |
| (Empty) |
| 1 # Copyright 2012 Google Inc. All Rights Reserved. | |
| 2 # | |
| 3 # Licensed under the Apache License, Version 2.0 (the "License"); | |
| 4 # you may not use this file except in compliance with the License. | |
| 5 # You may obtain a copy of the License at | |
| 6 # | |
| 7 # http://www.apache.org/licenses/LICENSE-2.0 | |
| 8 # | |
| 9 # Unless required by applicable law or agreed to in writing, software | |
| 10 # distributed under the License is distributed on an "AS IS" BASIS, | |
| 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 12 # See the License for the specific language governing permissions and | |
| 13 # limitations under the License. | |
| 14 | |
| 15 """ | |
| 16 Iterator wrapper that allows you to check whether the wrapped iterator | |
| 17 is empty and whether it has more than 1 element. | |
| 18 """ | |
| 19 | |
| 20 class PluralityCheckableIterator(object): | |
| 21 | |
| 22 def __init__(self, it): | |
| 23 self.it = it.__iter__() | |
| 24 self.head = [] | |
| 25 # Populate first 2 elems into head so we can check whether iterator has | |
| 26 # more than 1 item. | |
| 27 for i in range(0, 2): | |
| 28 self.__populate_head__() | |
| 29 | |
| 30 def __populate_head__(self): | |
| 31 try: | |
| 32 e = self.it.next() | |
| 33 self.underlying_iter_empty = False | |
| 34 self.head.append(e) | |
| 35 except StopIteration: | |
| 36 # Indicates we can no longer call next() on underlying iterator, but | |
| 37 # there could still be elements left to iterate in head. | |
| 38 self.underlying_iter_empty = True | |
| 39 | |
| 40 def __iter__(self): | |
| 41 while len(self.head) > 0: | |
| 42 yield self.next() | |
| 43 else: | |
| 44 raise StopIteration() | |
| 45 | |
| 46 def next(self): | |
| 47 # Backfill into head each time we pop an element so we can always check | |
| 48 # for emptiness and for has_plurality(). | |
| 49 self.__populate_head__() | |
| 50 return self.head.pop(0) | |
| 51 | |
| 52 def is_empty(self): | |
| 53 return len(self.head) == 0 | |
| 54 | |
| 55 def has_plurality(self): | |
| 56 return len(self.head) > 1 | |
| OLD | NEW |