[Python-ideas] if condition: break idiom

Josiah Carlson josiah.carlson at gmail.com
Sat Sep 20 21:44:45 CEST 2008


On Sat, Sep 20, 2008 at 12:07 PM, Brett Cannon <brett at python.org> wrote:
> On Sat, Sep 20, 2008 at 11:35 AM, Arnaud Delobelle
> <arnodel at googlemail.com> wrote:
>> Hello,
>>
>> It seems to me that a lot of the time that I use a break statement, it is
>> directly after an if.  Typically:
>>
>> while True:
>>    do something
>>    if condition:
>>        break
>>    do something else
>>
>> I don't like so much the if .. break which is spread over two lines.  Of
>> course I could write
>>
>> while True:
>>    do something
>>    if condition: break
>>    do something else
>>
>> It doesn't read so well either IMHO. I think that this would look better:
>>
>> while True:
>>    do something
>>    break if condition
>>    do something else
>>
>
> For some reason this suggestion reminds me of Icon.
>
> Anyway, so I take it this suggestion is to extend the break statement
> to have an 'if' trailer? Or are you trying to make 'break' an
> expression?
>
> If you are after the former, the problem with that is that the
> special-casing of 'if' might confuse people because they will suddenly
> want an 'else' clause. Adding that might then cause a naive user to
> see ``break if x`` and then think 'break' is an expression.
>
> Which leads to its own issues. How do you implement 'break' as an
> expression? It doesn't make much sense to have ``fxn(a, break, b)``
> inside a loop. And you can't say 'break' can only appear in the true
> clause of an 'if' expression as that is too specialized and will lead
> to potential misuse of the statement (or at least an attempt).
>
> I don't see enough benefit from the change to warrant dealing with any
> of the above issues.

It gets worse ;)

  break if condition

Also implies...

  continue if condition

Never mind

  break if condition else continue
  continue if condition else break

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

or
  continue if condition
  break

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.

 - Josiah



More information about the Python-ideas mailing list