by rich_sasha · 4y ago · 0 comments
Genuinely useful feature that is awkward to emulate? Nah.
Let's face it, everyone writes a double or triple nested for loop every now and then.
Exactly; at least for me the other features you mention I use daily (or when considering coding hours only, multiple times per hour), whereas I cannot even exactly remember when the last time was I had to break out of a nested loop. I'm not saying it's not useful, just that I don't think that code frequency is a useful argument to make here, especially not in comparison with the features you mention.
This feels like a bunch of people projecting their subjective biases on what code should look like on everyone else. Python 2/3 all over again (in a small teacup).
Python is already expressive enough that unlabeled break and continue are usually the wrong choice.
Citation needed. You can of course write code so they are not needed, but it won't necessarily be clearer, more efficient or "better" in any way.
That sometimes they facilitate spaghetti code is no reason no ban them.
If efficiency truly matters, you should not be using break or continue, you should be using a vectorized processing library like numpy or pandas.
The pattern I describe in https://news.ycombinator.com/item?id=32710822 works for continue, and the same general concept works for break (and note that I've made this as unappealing as possible for my refactor, and it's still not really worse, but could easily be made even better):
for i in x:
if cond(i):
break
return do_a_thing(x)
can become def find(x):
for i in x:
if cond(i):
return i
do_a_thing(find(x))
and these two patterns generalize to most more complex examples, and are fundamentally easier to follow, as the code is doing fewer things at any given time!Like break and return from a loop are equivalent modulo implicit state, and the same is true for continue and a conditional generator.
Not all loops ate numeric, in fact most aren't (since vectorisable stuff already is vectorised).
"Break and continue are almost always the wrong choice" is not, and indeed dissing one the oldest and most retained features in programming language history requires substantial justification.
But for those you've got iterools.concat, or generator comprehensions.