The rap against "while True:" loops

kj no.email at please.post
Sun Oct 11 00:02:37 CEST 2009


In <01ccc46d-5ea9-4dfe-ba22-699c6b859f00 at v36g2000yqv.googlegroups.com> Mensanator <mensanator at aol.com> writes:

>On Oct 10, 3:15=EF=BF=BDpm, kj <no.em... at please.post> wrote:
>> I'm coaching a group of biologists on basic Python scripting. =EF=BF=BDOn=
>e
>> of my charges mentioned that he had come across the advice never
>> to use loops beginning with "while True". =EF=BF=BDOf course, that's one
>> way to start an infinite loop, but this seems hardly a sufficient
>> reason to avoid the construct altogether, as long as one includes
>> an exit that is always reached. =EF=BF=BD(Actually, come to think of it,
>> there are many situations in which a bona fide infinite loops
>> (typically within a try: block) is the required construct, e.g.
>> when implementing an event loop.)
>>
>> 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? =EF=BF=BDHas it reached the status of "bes=
>t
>> practice"?

>If you know this "exit that is always reached",
>why do you pretend not to know it by writing
>"while True"?

There's no "pretense" of anything.  I just happen to prefer the
directness of this:

while True:
    ...
    if test_that_always_succeeds_eventually():
         break
    ...

over the unnecessary fussiness of this:

my_prissy_little_indicator_variable = True
while my_prissy_little_indicator_variable: 
    ...
    if test_that_always_succeeds_eventually():
        my_prissy_little_indicator_variable = False
        continue  # oh boy this is going to be fun!
    ...

In fact, if it were up to me, I would have made the fundamental
looping construct something like

repeat:
      ...
      if whatever():
           break
      ...

and made all the other looping constructs as syntatic sugar for
this one.

kj



More information about the Python-list mailing list