r/Python • u/Nausicaa23Pencil • 1d 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?
166
u/BorgCant3en 1d 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.
20
u/CreeperSlimePig 1d 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)
12
u/Outside_Complaint755 1d 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.
20
u/Temporary_Pie2733 1d 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.
8
u/deckardscone 1d 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.
10
u/marr75 1d 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 1d 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.
13
u/Individual-Flow9158 1d ago
Your codebase has far bigger problems, OP.
strictisn't going to be renamed now, after all this time, just because you feel mislead.4
u/zunjae 1d ago
AI slop Reddit post
2
u/binaryfireball 1d ago
Your problem is that you have to call zip a lot. Fix your data
1
u/--Apk-- 14h ago edited 38m 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.
1
u/bob_f332 11h ago
Check list lengths beforehand.
1
u/DEE_PIZZLE 8h 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.
1
u/mgedmin 6h 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/Wonderful-Habit-139 1d 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.
0
u/nicholashairs 23h 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)