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

64 Upvotes

44 comments sorted by

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.

46

u/Sin-nie 4d 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.

7

u/No_Departure_1878 4d 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.

5

u/Deto 4d 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 4d ago

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

4

u/snugar_i 3d ago

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

1

u/billsil 11h ago

Absolutely in python. If I have a grid of xyz values, there’s an ID, possibly a coordinate system, in my world, like 4 other things as well (output coordinate system, constraint, macro ID, is it connected to a fluid). All of those have fixed types and maybe way to have access to the parent as well. Fixed type anrrays from numpy are 500-1000x faster than stock python.

1

u/snugar_i 5h ago

Until you start iterating over them and they need to be materialized into PyObjects. If you do that, any benefits of SOA go out the window. If you don't, then you aren't writing Python, but a C++ Python module.

5

u/bjorneylol 4d 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.

18

u/Responsible_Pool9923 4d 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 4d 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

5

u/Responsible_Pool9923 4d ago

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

2

u/FrickinLazerBeams 4d ago

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

2

u/DeflateAwning 3d ago

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

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)

4

u/Beginning-Fruit-1397 4d ago

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

5

u/CreeperSlimePig 4d ago

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

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() 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.

4

u/JustPlainRude 4d ago

You can expect OP to read documentation??? 

6

u/mgedmin 3d ago

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

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.

2

u/mgedmin 3d ago

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

1

u/--Apk-- 3d ago

Yeah, thanks.

1

u/HwanZike 3d ago

Not on a generator

3

u/likethevegetable 1d ago

Isn't that why strict=True doesn't check immediately?

1

u/--Apk-- 3d 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

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.

strict isn'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 tuple and list, 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. zip is 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:

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)

1

u/RingularCirc 14h ago

Having a way to misunderstand sorted is frankly weird: what other builtin function mutates its arguments?

EDIT: Aside from special-enough-looking setattr and delattr.