[Python-ideas] for/else syntax

Ron Adam rrr at ronadam.com
Sat Oct 3 17:00:48 CEST 2009



Nick Coghlan wrote:
> Steven D'Aprano wrote:
>> And in fact, it is legal to have for loops without a break but include 
>> an else. Is it useful? I don't know, but Python can't forbid them 
>> without breaking (pun not intended) code like this:
>>
>> for x in xs:
>>     if __debug__:
>>         break
>> else:
>>     print "whatever"
>>
>> "if __debug__: suite" is special: the Python compiler optimizes the 
>> entire suite away when running with the -O flag. So if Python would 
>> treat the presence of an else as an error unless there was a break, you 
>> could have some code which was, or wasn't, legal according to the 
>> presence of the optimize flag. This is clearly a Bad Thing.
>>
>> Hence, even if for...else with no breaks are useless, they must be 
>> allowed.
> 
> A SyntaxWarning should still be OK though - having an else clause that
> can only be reached in debug mode is pretty dubious in its own right.
> 
> Cheers,
> Nick.


How about this?

    try:
       for x in xs:
           foo()
       esle:
           Print "foo didn't raise an exception."
    except:
       print "foo riased an exception"

Using exceptions for flow control is very common in python.


Or this:

    for x in xs:
        y = foo()
        if y is True:
           return
    else:
        Print "y was never True"

This is perfectly acceptable in my opinion.


The explicit spelling of the "else in a "for/else" is closer to.

     for x in xs:
        do something
     elif x == xs[-1]:
        do something more

But that isn't reliable if x or xs is modified inside the loop.  So a 
better way to say it is:

     for x in xs:
        do something
     elif for.finished:
        do something more

But of course since a for loop isn't an object with a name, we can't look 
at it directly to see what it's status is.  I think we just need a really 
nice tutorial on using for-else's.

Ron

























More information about the Python-ideas mailing list