Reject Mismatched Python Iterables with zip strict
A game content export contains one list of asset IDs and a separate list of download paths. An exporter bug omits the last path. An importer using ordinary zip() appears to succeed, but the last asset never reaches the manifest.
Use zip(strict=True) when each input position must have a partner. This Python 3.10 or later recipe focuses on finite, small batches and on detecting missing positions before calling an external writer.
Reproduce Silent Truncation
Run this small example:
| |
The default call returns two pairs, silently discarding the unmatched tail. Strict mode turns the violated equal-length assumption into an exception. It accepts generators as well as lists, so it does not require both inputs to support len().
The built-in zip documentation describes both behaviors. Strict mode checks how many items arrive; it does not verify that a path belongs to the asset ID beside it. Two equally long lists can still be misaligned.
Understand When the Error Happens
Constructing a strict zip object does not inspect every item. The mismatch appears only as iteration reaches the unequal ending. A loop can already have processed valid pairs by then:
Replacing applied.append() with a database write would leave an update already applied when the exception arrives. Strict iteration supplies detection, without rollback. Breaking out of the loop early also leaves the unvisited suffix unchecked.
PEP 618 introduced this option in Python 3.10. Its specified failure point is the unequal exhaustion boundary. Treat the inputs as consumed after an attempted pass: fetching items and detecting a mismatch can advance their iterators, including an unmatched item. Reusing the same iterators is not a reliable retry strategy.
Prepare the Whole Batch Before Writing
For a small batch, collect all pairs first. Save this as asset_pairs.py:
| |
The writer receives no calls until collection and validation finish. A length mismatch, input-iterator exception, empty string, or duplicate ID prevents every writer call. IDs are exact, case-sensitive strings; the helper does not trim them. Paths are opaque nonempty strings here, with no filesystem or URL validation.
Collect tuples before converting to a dictionary. Otherwise repeated IDs could overwrite earlier entries before the application notices the export error. Both empty inputs represent an empty batch; one empty input and one nonempty input are an error.
The helper’s boundary is deliberately limited: a failure inside write_pair can still leave earlier writes applied. Use a database transaction or a separate staged publication step if the writes themselves must commit together.
Test Both Mismatch Directions and Late Failures
Save this beside the module as test_asset_pairs.py and run python -m unittest -v test_asset_pairs:
| |
Test the exception type instead of matching the interpreter’s exact diagnostic text. Both mismatch directions matter, and the late invalid-value cases ensure that one acceptable first pair does not trigger a premature write.
Choose the Appropriate Batch Boundary
This approach holds the complete paired batch in memory. It suits small manifests and bounded configuration exports. Infinite inputs cannot be fully validated this way, and very large imports need a different staging design.
For a large import, stage records in a temporary store, finish reading and validating, then publish through the store’s transaction or commit mechanism. Direct streaming writes require a deliberate partial-progress or rollback policy.
When unequal lengths are intentional, choose the policy explicitly: ordinary zip() keeps only the shared prefix, while itertools.zip_longest() retains extra positions with a fill value. For parallel asset fields that must match, strict iteration plus a completed preparation step makes missing positions visible before external updates begin.