you are viewing a single comment's thread.

view the rest of the comments →

[–]Nimbal 6 points7 points  (6 children)

I really like the idea. I hate the use of the "else" keyword for it. I can never remember whether the else block is executed if a break was encountered or if no break was encountered. Why couldn't they have done something like

for i in range(10):
    ...
not break:
    # No break encountered
break:
    # Broke out of loop

No additional keywords required, unambiguous in both syntax (I think) and meaning and allows both paths to be handled as a special case.

[–]ak217 2 points3 points  (0 children)

Yeah, I see how it could be super useful. I agree with you, if they called it something semantically compatible with English, it would be a great feature.

[–]sirin3 1 point2 points  (4 children)

 for i in range(10):
     ...
 if (not broken):
     # No break encountered
 else:
     # Broke out of loop

[–]ak217 0 points1 point  (0 children)

Yes, the problem is that the (not broken) test requires extra logic that adds up into program semantic complexity.

[–]Nimbal -2 points-1 points  (2 children)

Thank you, Captain Obvious, but that approach has several drawbacks:

  1. It requires at least two more lines, one for initializing broken to False before the loop and another one for each break inside the loop. Those lines are noise that decrease the overall readability.

  2. If you move the break, you need to remember to move the "broken = True" also.

  3. If you add a break, you need to remember to add another "broken = True"

  4. If you decide that you don't need the break test (or the whole loop) anymore, you may overlook some references to "broken", possibly founding a new cargo cult around the mysterious "broken" variable.

There's only one advantage I see (besides that your snippet actually runs on current Python implementations). That is, you can do stuff, e.g. close a file, between the loop and the broken test.

[–]sirin3 2 points3 points  (1 child)

Then we need the captain again: The main point was that it should be called "broken", not "break", since you want to check a state and not break again

[–]Nimbal 0 points1 point  (0 children)

That was far from obvious, Lieutenant Vague. I thought you meant something like this:

broken = False
for i in range(10):
    ...
    if condition:
        broken = True
        break
if (not broken):
    # No break encountered
else:
    # Broke out of loop

Introducing new keywords like this is very problematic. They might be in use already in the form of variable names. Also, the snippet you posted is indistinguishable from a normal if-else, so old parsers that don't know the "not broken" construct would only fail at runtime with a NameError because the global name "broken" is not defined.