Skip to content
Sarj Code Standards

prefer-itertools-batched

Iterate fixed-size chunks with itertools.batched instead of restating the batch size in a slice.

Why

A range step and a slice width express the same batch size twice and can drift independently. itertools.batched states the width once and includes a final partial batch.

Fix

Import batched from itertools and iterate batched(sequence, size, strict=False). Review consumers because each batch is a tuple. Omit strict=False when supporting Python 3.12.

Examples

Before — flagged The range and slice repeat the batch size
batches.py
def run(files, size):
for offset in range(0, len(files), size):
consume(files[offset : offset + size])
After — preferred batched owns the batch size
batches.py
from itertools import batched
def run(files, size):
for batch in batched(files, size, strict=False):
consume(batch)