[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses (original) (raw)

Jan Kaliszewski zuo at chopin.edu.pl
Sat Jun 9 18:01:13 CEST 2012


Nick Coghlan dixit (2012-06-08, 19:04):

for x in iterable: ... except break: # Implicit in the semantics of loops pass else: ...

Would it be worth adding the "except break:" clause to the language just to make it crystal clear what is actually going on? I don't think so, but it's still a handy way to explain the semantics while gently steering people away from linking for/else and if/else too closely.

IMHO a better option would be a separate keyword, e.g. 'broken':

for x in iterable:
    ...
broken:
    ...
else:
    ...

And not only to make the 'else' more understandable. I found, in a few situations, that such a 'broken' clause would be really useful, making my code easier to read and maintain. There were some relatively complex, parsing-related, code structures...

stopped = False
for x in iterable:
    ...
    if condition1:
        stopped = True
        break
    ...
    if contition2:
        stopped = True
        break
    ...
    if contition3:
        stopped = True
        break
    ...
if stopped:
    do_foo()
else:
    do_bar()

It would have been nice to be able to do:

for x in iterable:
    ...
    if condition1:
        break
    ...
    if contition2:
        break
    ...
    if contition3:
        break
    ...
broken:
    do_foo()
else:
    do_bar()

Cheers. *j



More information about the Python-ideas mailing list