Last active
August 29, 2015 14:20
-
-
Save ianjosephwilson/3c63309781d940233669 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 BatchIterator(object): | |
""" | |
Return batches of items of batch size or less from the given source. | |
Each batch is another iterator. | |
""" | |
def __init__(self, source, batch_size=900): | |
self.source_iter = iter(source) | |
self.batch_size = batch_size | |
self.stop_iteration = False | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if self.stop_iteration: | |
raise StopIteration | |
def batch(): | |
for item in self.source_iter: | |
self.index += 1 | |
yield item | |
if self.index % self.batch_size == 0 and self.index != 0: | |
break | |
else: | |
self.stop_iteration = True | |
return batch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment