[Python-ideas] if condition: break idiom

Arnaud Delobelle arnodel at googlemail.com
Sat Sep 20 22:26:43 CEST 2008


On 20 Sep 2008, at 20:44, Josiah Carlson wrote:

>> On Sat, Sep 20, 2008 at 11:35 AM, Arnaud Delobelle
>>> [...] I think that this would look better:
>>>
>>> while True:
>>>   do something
>>>   break if condition
>>>   do something else
>>>
>>
>> It gets worse ;)
>
>  break if condition
>
> Also implies...
>
>  continue if condition
>

That's true, why not?  I don't use use continue so much but it seems  
logical.

> Never mind
>
>  break if condition else continue
>  continue if condition else break
>

No that would be silly.

> Because who would want to write...
>  break if condition
>  continue
>
> or
>  continue if condition
>  break
>

The problem is: when would you need to do this?  I pointed out in my  
original post that almost half of uses of 'break' in the py3k python  
source come immediately after an 'if'.  Now I have never used or seen  
this:

     if condition:
         break
     continue

What would be the point of spelling it 'break if condition else  
continue'?  It would even defeat the idea behind my suggestion, which  
is to make the structure of a loop more obvious when you scan code:  
you can spot the 'break if' (and 'continue if'!) statements just by  
scanning the left hand side of the loop body.

> But if we can break or continue, why not others?  What's wrong with a
> raise (especially if we surround everything with parens...)?
>
>  (raise Exception("X")) if condition
>
> Never mind assert, yield, throw, return, ...  I hope this horse is  
> dead now.
>

You have implied one reason why not: raise, assert, yield, throw,  
return all take an argument which can be an if-expression, so this  
would make those statements difficult to parse if you are human (and I  
suspect impossible if you are the Python parser).

The fact that neither break nor continue take arguments makes them  
very 'poor' in the amount of meaning they convey.  That's why a lot of  
people feel like writing the following in one single line.

     if condition: break

Moreover, because we don't have a 'do .. while' construct, 'break' is  
more important than in other languages to shape loops (especially  
while loops), so I thought it would be useful to make it easier to  
spot.  The same argument can be made about 'continue' of course.

> - Josiah

-- 
Arnaud




More information about the Python-ideas mailing list