I use zip(strict=True) to catch mismatched inputs. If the loop sends emails or writes to a database, can some of those actions happen before the mismatch is detected? What are the safer options?
Can zip(strict=True) raise an error after the loop has already done work?
Answers
Yes. zip produces pairs lazily, so the loop processes each pair as it arrives. If one input runs out before the other, ValueError is raised when iteration reaches that point. Any earlier emails or writes have already happened.
For small inputs, turn the strict zip into a list before doing the work. That forces the length check to finish first. It uses memory for all the pairs, though, and it consumes one-shot iterators.
Reply to this answer
If both inputs are stable, sized collections, compare their lengths before starting. You can still keep strict=True in the zip as a check during iteration.
That doesn't work generally for streams or generators. They may not have a length, and checking them by consuming them leaves you without the original iterators to process. For large inputs, consider staging the data before committing side effects, or using a transaction where the operation supports one. Emails can't simply be rolled back.
Eddie:
Equal lengths only establish the count. They don't prove that each user is paired with the right address.
Reply to this answer
I'd question the two parallel collections in the first place. If an address belongs to a user, keep the relationship together in a record or object rather than relying on positions staying in sync.
That still needs a suitable model when a user has multiple addresses for different purposes, but at least the relationship is explicit.
Reply to this answer
The same timing issue comes up with itertools.batched(..., strict=True). It yields complete batches as it goes, then raises ValueError if the final batch is incomplete. If each batch is written immediately, those earlier writes may already be done.
Reply to this answer
Add your answer
Answers are reviewed before publication.
c.582~brinwexo:
So strict catches the mismatch, but it doesn't make the loop atomic. That's the distinction I was missing.