[Python-ideas] for/else syntax

Ron Adam rrr at ronadam.com
Sat Oct 3 20:50:19 CEST 2009

Masklinn wrote:
> On 3 Oct 2009, at 18:19 , Ron Adam wrote:
>> Yuvgoog Greenle wrote:
>>> Document it as much as you want but the "else" doesn't hint or clue as
>>> to whether it catches breaks or is skipped by them.
>>> The next problem's gonna be at midnight when you're reading code and
>>> asking yourself "hmmm, for, blah blah, else, hmm oh yeah, else-break,
>>> so this else occurs whenever there's a break."
>> True, and that is part of the other 20% I expect the documentation 
>> would't help.
>> The only solution to that that I can think of is to change the esle's 
>> in for and while loops to for/then and while/then in Python 5.0.
> That would yield
>     for val in vals:
>         if cond(val):
>             break
>         # processing
>     then:
>         # more stuff
> how does it make the "alternate" clause being skipped in case of break 
> any clearer?

I didn't say the behavior would change.

     for val in vals:
        if cond(val):
        # processing val
     then:   #all values processed
        # do more stuff

The break would brake out of the entire for/then block.

     for val in vals:
        if found(val):
           searchval = val
     then:  # if not found
        searchval = default

     # breaks jumps to here

I think that reads very well. :-)

On the other hand "else" with the same comments really isn't all that much 
worse once you understand how break works in for/while loops.  It's just a 
bit more of a hurdle for people new to python to get because of it's 
counter intuitive behavior compared else's use in if/else blocks.

In those other languages that use case blocks, break is used to escape out 
of the entire case block in the same way break escapes out of the entire 
for/else blocks in python.


More information about the Python-ideas mailing list