Complete worked example
python
from itertools import islice
def inspect_example(values, size):
if type(size) is not int or size <= 0:
raise ValueError('positive batch size required')
consumed = []
def source():
for value in values:
consumed.append(value)
yield value
stream = source()
batches = []
while batch := list(islice(stream, size)):
batches.append(batch)
return {'batches': batches, 'consumed': consumed}- Reasoning
- The program obtains an iterator and repeatedly takes at most size records with islice. A nonempty slice becomes the next batch; an empty slice ends the loop. This preserves source order and retains the remaining records even when they do not fill a complete group.