The rap against "while True:" loops

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Oct 13 00:48:18 EDT 2009


On Mon, 12 Oct 2009 11:32:27 -0700, Mensanator wrote:

>> Nothing wrong with a having a break IMHO.
> 
> My opinion is that there is everything wrong with having a break. I
> don't think I have ever used one, I write code that doesn't depend on
> that crutch.


Using break can avoid a lot of complication in loops. There's no need to 
force every loop to have a single exit point (or for that matter, for 
every function to have a single return). Compare the straightforward 
implementation of a simple linear search:

for item in seq:
    if cond(item):
        print item
        break

versus doing it without a break:

found = False
for item in seq:
    if not found and cond(item):
        print item
    
or:

found = False
seq = iter(seq)
while not found:
    item = seq.next()
    found = cond(item)
    if found:
        print item

The first is obviously correct, and efficient (it stops searching when it 
has found a result). The second and third avoid using a break, but at the 
cost of complicated, inefficient code which isn't obviously correct. If 
you need to post-process item before returning, it's simple to replace 
the return with a break.


> The best way to avoid the pitfalls of spaghetti code is to not write it
> in the first place.


break does not necessarily lead to spaghetti code. Avoiding break just 
because it is a "goto" is cargo-cult programming -- following the magic 
incantations with no understanding of the *reasons* for when gotos should 
be used and avoided.

The danger with goto is that it is an *unstructured* jump. break, 
continue, return, yield, for, while are all *structured* jumps. They can 
be abused, like anything, but they're not inherently dangerous.



-- 
Steven



More information about the Python-list mailing list