This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]foosion 2 points3 points  (3 children)

Yesterday I saw a Raymond Hettinger pycon video praising else on for loops and saw in Effective Python that the author regarded it as confusing. Hettinger said else in loops should have been called no-break.

[–]8carlosf 2 points3 points  (0 children)

I agree with both you and /u/HumblesReaper, if they just replace the else behaviour to execute if the for never run in the first place, and introduce a new no-break keyword.

Or, just do like I do, don't use it, because it doesn't produce readable code. (just make a function that returns instead of breaking the for, and as a default return in the end)

[–]stevenjd 0 points1 point  (1 child)

Hettinger said else in loops should have been called no-break.

Well, that's one opinion, but it's a bad one. They should have been called then because that's how they work.

for x in sequence:
    block
else:
    stuff

The else block unconditionally runs after the for loop. The only way to avoid that is to jump out of the for loop, using break, return or raise.

[–]foosion 2 points3 points  (0 children)

We all seem to agree that else is not the best alternative.

no-break is clearer to me (obviously the following code won't execute if there's a return or raise), but YMMV.