Python batched strict mode can fail after yielding valid batches
Use strict=True when every batch must have the requested size. In Python 3.13, that check happens as the iterator is consumed: earlier complete batches may already have reached the caller when the short final batch raises ValueError.
Run the example
Tested on Linux with Python 3.13.5. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_strict_batches.py in that directory. Use this filename to avoid shadowing a standard-library module.
from itertools import batched
delivered = []
try:
for batch in batched(range(5), 2, strict=True):
delivered.append(batch)
print("Delivered:", batch)
except ValueError as error:
print("Rejected tail:", error)
print("Previously delivered:", delivered)
print("Default tail:", list(batched(range(5), 2)))Run it:
python3.13 demo_strict_batches.pyCaptured output:
Delivered: (0, 1)
Delivered: (2, 3)
Rejected tail: batched(): incomplete batch
Previously delivered: [(0, 1), (2, 3)]
Default tail: [(0, 1), (2, 3), (4,)]Interpret the result
The first two tuples remain in delivered; strict mode does not undo earlier work. The incomplete tuple is consumed but never yielded. If an application needs validation before any side effect, first materialize all batches for a finite input that fits memory, then process them. That still consumes the source and cannot undo side effects inside its iterator. For large streams, use a transaction or a separate validation design. batched() exists in Python 3.12, but its strict option requires 3.13.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_strict_batches.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.