r/Python • • 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?

50 Upvotes

36 comments sorted by

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.

41

u/Sin-nie 1d ago

I don't think there is an argument not to represent a user and their email address in any way where they can become desynced.

This sort of thing should be stored in a class.

5

u/No_Departure_1878 20h ago

Totally, zip there should not exist, it should be a loop over users and you could get the name and email from each user as a property. You can't fix bad design with zip.

4

u/Deto 1d ago

Yep! Better code/design is often better because it makes it harder to make a mistake (or at least, harder to make a quiet mistake).

3

u/Chroiche 1d ago

99% of the time I agree, but there can be performance reasons for using an object of collections over a collection of objects

2

u/snugar_i 5h ago

Definitely. In C++. In Python, not so much

5

u/bjorneylol 1d ago

there are situations where you may need to store arbitrary sets of contact information for someone, e.g. accounting software you may have a a different email address for each of receivables, payables, sales, or maybe they have multiple warehouses with different contacts, etc.

17

u/Responsible_Pool9923 1d ago

Then use dedicated contact objects each referencing the user. Since data has to come from somewhere, an SQL table with contacts related to users via foreign key makes most sense.

2

u/bjorneylol 1d ago

That does nothing to prevent zip(users, ar_emails, strict=True) from throwing an error if a user only has an AP contact set up, or if you have a wayward WHERE clause in your JOIN. The bottom line is that zip(strict=True) is the wrong tool to validate a 1:1 relationship between user and contact information

4

u/Responsible_Pool9923 1d ago

Of course. The OP example with users makes very little sense, we're on the same side of the argument.

2

u/FrickinLazerBeams 23h ago

It makes sense as an example, or in some legacy codebase where shitty data structures already exist, or probably a dozen other scenarios.

1

u/DeflateAwning 6h ago

You've accurately expressed my #1 gripe with numpy being used everywhere

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)

4

u/Beginning-Fruit-1397 21h ago

Not impossible tho. length_hint can be exact for Sequence iterators, akin to rust ExactSizedIterator

3

u/CreeperSlimePig 16h ago

yeah, but you can't just reject a strict zip for having different length hints

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() is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use the strict=True option. Its output is the same as regular zip(): {code example}

Without the strict=True argument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.

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.

3

u/JustPlainRude 22h ago

You can expect OP to read documentation??? 

2

u/mgedmin 6h ago

No, but you can blame them later for not reading it. Very handy feature, that.

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.

strict isn'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.

2

u/mgedmin 6h ago

Did you mean len() rather than min()?

•

u/--Apk-- 37m ago

Yeah, thanks.

•

u/HwanZike 31m ago

Not on a generator

•

u/--Apk-- 27m ago

True but it wouldn't affect the big O as the emails and users are being realised in the for loop anyway.

EDIT: to be clear you'd just materialise them

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:

a = [3,2,1]

sorted(a) # wrong! A is still [3,2,1]
b = a.sort() # wrong! B is now None

b = sorted(a) # b is now [1,2,3]
a.sort() # a is now [1,2,3]

(Yes yes technically a is sorted earlier if you run this code verbatim)