The rap against "while True:" loops

Peter Billam peter at www.pjb.com.au
Sat Oct 10 19:52:13 EDT 2009


On 2009-10-10, kj <no.email at please.post> wrote:
> I use "while True"-loops often, and intend to continue doing this
> "while True", but I'm curious to know: how widespread is the
> injunction against such loops?  Has it reached the status of
> "best practice"?

This trend is ironic; I remember in the structured-programming
revolution the
   loop { ... if whatever {break;} ... } 
idiom was The Recommended looping structure, because the code is
more maintainable.  With a   while () {...}   idiom, you commit
yourself to a bug-prone rewrite if you ever need to insert a
statement before the first break-test,  and likewise with a
repeat { ... } until ()   you commit yourself to a rewrite if
you ever need to insert a statement after the last break-test.
Also, it replaces a multitude of idioms (while, repeat, for,
foreach, map, ...) with one simple idiom which works in all
cases, including in all languages (OK, except functional).

The   for item in list   idiom is wonderfully readable if you
know that's all you'll ever want to do,  but for more general
loops there are still arguments in favour of   while True

Infinite loops, well they're quickly noticed in development,
just like stack-crashes are in stack-based languages.
They can occur in other loop-idioms too, like if you
append to your list, or adjust the looping index.

JMHO,  Regards,  Peter

-- 
Peter Billam       www.pjb.com.au    www.pjb.com.au/comp/contact.html



More information about the Python-list mailing list