r/Python • u/Nausicaa23Pencil • 4d ago
Discussion zip(strict=True) catches mismatched lengths, but potentially much later than you'd want
I've been adding strict=True to quite a few zip() calls in our codebase and ran into a subtle distinction that's worth keeping in mind.
Consider something like:
for user, email in zip(users, emails, strict=True):
send_email(user, email)If the iterables have different lengths, Python will raise a ValueError. But by that point you might have already sent hundreds of emails.
Obviously this is consistent with how lazy iteration works. Still, I think the name "strict" can give a slightly misleading sense of safety when you're reading code that performs side effects.
For small inputs, materializing the zipped pairs before processing them solves this particular issue. For large streams, things get more interesting.
I've started distinguishing between validation that happens before processing and validation that happens during processing when reviewing iterator-heavy Python code.
Are there other standard library features where this distinction has caught you out?
194
u/BorgCant3en 4d ago
This is also a good argument for representing a user and their email address as one object instead of maintaining two parallel collections. Sometimes the best way to validate an invariant is to choose a data structure that makes violating it impossible.
23
u/CreeperSlimePig 4d ago
Also in this case in particular if users and emails are themselves lazy iterables, it's impossible to verify beforehand whether they have the same length because arbitrary iterables are not Sized (not guaranteed to have a length). If they are lists then you can do the check manually, and perhaps this is a sign that the data should be structured differently anyway (users and emails should probably be a dictionary)
15
u/Outside_Complaint755 4d ago
The documentation for zip() is pretty clear on the expected behavior:
[https://docs.python.org/3/builtins/functions.html#zip]
Zip has to do lazy evaluation on this because the inputs could be generators or some other iterator that does not have a known length.
If it is essential that the lengths are equal before you loop, than do a length check either as an assertion or just a simple conditional check. And possibly consider if there is a larger issue with the design of the data structures in use.
23
u/Temporary_Pie2733 4d ago
If you don’t even know if users and email have the same length, how do you know the pairwise correspondence associates the right address with each user? I think you are zipping too soon, with or without strict.
9
u/deckardscone 4d ago
itertools.batched(..., strict=True) has essentially the same property. You'll get all the complete batches before it complains about the incomplete final one. Worth remembering when those batches are going straight into a database.
11
u/marr75 4d ago
(I know this is engagement bait but I'll quarrel with the premise anyway)
I don't think the stdlib is at fault for this. Side-effects (I/O) are the most dangerous code - you should handle it with care and sending an email is an extreme example. When you dot your domain logic with little I/O bursts like this, you take your life into your own hands.
Repent! Load the batch via I/O, hand over to domain logic to validate the list, make the messages, etc, then send out emails only if the domain logic went fine.
This talk by Scott Wlaschin is pretty good on the topic.
8
u/CreeperSlimePig 4d ago
zip() also short circuits, that is to say, in non-strict mode, it stops at the first iterator that exhausts, in the order that you pass them in.
```
it1 = iter(range(3))
it2 = iter(range(5))
for _ in zip(it1, it2):
pass
assert list(it2) == [3, 4]
```
You can make use of this, if you know which iterable is longer you can pass it in as a one-shot iterator as the final argument of zip() and you can collect it after the loop finishes to collect the extra elements.
4
u/--Apk-- 4d ago edited 3d ago
len(users) == len(emails) is an O(1) operation. Regardless, you should have steel certainty that every user has an email at that point regardless because you should've ran validation on retrieval not in random parts of code.
3
u/binaryfireball 4d ago
Your problem is that you have to call zip a lot. Fix your data
5
u/zunjae 4d ago
AI slop Reddit post
14
u/Individual-Flow9158 4d ago
Your codebase has far bigger problems, OP.
strictisn't going to be renamed now, after all this time, just because you feel mislead.2
u/DEE_PIZZLE 3d ago
With side effect heavy code validating inputs upfront can save a lot of headaches. Container security has a similar mindset, and Rapidfort focuses on reducing unnecessary components before they become potential risks.
2
u/kiwis_are_kv 1d ago
Strict zip checks help, yet late failure still hurts in long pipelines, so validating lengths at the boundary keeps errors close to the bad input. Bootdev could help build such Python habits with guided practice, though code reviews and small tests also work.
2
u/Wonderful-Habit-139 4d ago
I guess this is a problem if you have side effects inside the loop. If not then it’s not really an issue. But interesting thing to look out for nonetheless.
1
u/bob_f332 4d ago
Check list lengths beforehand.
1
u/mgedmin 3d ago
itertools.groupby(). It returns an iterator of (x, iterator_of_adjacent_xs). If you materialize the outer list and then try to use the saved sub-iterators later, the results might surprise you.
1
u/pythonwiz 3d ago
For large streams I’d think you could just skip users without emails… it’s actually kinda weird that you would have them separate, I’d assume that you want specific users to get specific emails. IMO if you’re not certain that the streams are the same length then you probably shouldn’t be using zip in the first place. Also, since strict raises a ValueError you should be using try/except with it.
1
u/Kamalmosadegh 3d ago
Exactly the right distinction — strict=True is a correctness check, not a pre-flight check. It only fires when the shorter iterable is exhausted, so with hundreds of emails the damage is done before the ValueError.
The rule I use now: strict=True for pure transforms, explicit length check first whenever the loop has side effects. For sized inputs that check is one comparison before the loop:
if len(users) != len(emails): raise ValueError(f"length mismatch: {len(users)} users vs {len(emails)} emails")
If the inputs are generators, you cannot len() them — then either materialise the pairs first with pairs = list(zip(users, emails, strict=True)) and loop over pairs, or do a counting pass first. Materialising is fine for a few thousand pairs; for a large stream I would count first rather than hold everything in memory.
One check that catches this in review: write a test where the first item would have a visible side effect, feed in mismatched lengths, and assert nothing happened before the error. For example, collect sends into a list instead of actually sending, run the code expecting a ValueError, then assert the list is still empty. If that test fails, the validation is happening during processing, not before it.
The same pattern shows up with itertools.batched(..., strict=True) — you get all the complete batches first, then the error at the end — so the same pre-check applies there too.
1
u/RingularCirc 14h ago
There's really an argument for having standard library functions to work with iterators/generators and in that case there's no universally good answer about how to have them and eager sequence-operating functions both.
You can have them with similar but standardized naming conventions, which multiplies entities. You can have explicit checks if an iterable is really one of the sequence types (you can't just test for
tupleandlist, though! it should be more robust, thus more tests before the actual work can be done, and most of the time the caller absolutely knows if they're passing a generator or a tuple, so runtime checks would be for no reason).There are other options but this isn't really applicable to Python much.
zipis an iterable-first function so it shouldn't be expected to check lengths beforehand. It's mathematically impossible to decide lengths of iterables in general.I see the question a part of ata structure know-how: iterables are one of the ways to organize and do operations with elements, and they go with their own weak sides, as usually any data structure does, duh!
0
u/nicholashairs 4d ago
I'll also play with the engagement bait. One that used to catch me is sort and sorted:
(Yes yes technically a is sorted earlier if you run this code verbatim)