[Python-ideas] if condition: break idiom

Arnaud Delobelle arnodel at googlemail.com
Sat Sep 20 20:35:32 CEST 2008


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

Now I've had a quick look on a py3k tree (a bit old, rev. 64270):

$ grep -r --include "*.py" break py3k/ | wc -l
     1418

1418 uses of the break statement in the py3k python code.

$ grep -r --include "*.py" -B 1 break py3k/ | grep if | wc -l
      680

Of which 680 are immediately preceded by an if statement

$ grep -r --include "*.py" "if .*: break" py3k/ | wc -l
      107

Of which 107 are preceded by an if on the same line

This means that:

* 48% of uses of "break" are directly after an "if"
* this has been written on one single line about 16% of the time.

(I know my greps will include a few false positive but I don't think  
they are significant :)

-- 
Arnaud




More information about the Python-ideas mailing list