def _batches(iterable, size):
    """
    Take an iterator and yield its contents in groups of `size` items.
    """
    sourceiter = iter(iterable)
    while True:
        try:
            batchiter = islice(sourceiter, size)
            yield chain([next(batchiter)], batchiter)
        except StopIteration:
            return
Take an iterator and yield its contents in groups of `size` items.