The rap against "while True:" loops

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Oct 11 18:15:16 CEST 2009


En Sat, 10 Oct 2009 19:32:25 -0300, Björn Lindqvist <bjourne at gmail.com>  
escribió:

> I have many times screwed up "while True"-loops. When I thought I had
> a safe exit condition which turned out to be never reached in some
> rare corner cases. Leading to weird bugs with hanging threads. I have
> seen colleges screw up in the same way too.

But that's not a problem with the "while True:" construct, that's a  
problem with your condition. Had you written the code using "while  
some_condition:" it would have failed in the same way.

> [...] Recursive functions
> can also be more readable than "while True" because it is easier to
> make the exit condition explicit. But sometimes they are necessary and
> then you have to be careful to check that the "while True" always
> breaks somewhere.

That's true for any loop. The only difference is, with a "while  
condition:" loop, the condition is right at the while statement. In a  
"while True:" loop, you have to look for the condition elsewhere (likely,  
an "if" statement preceding a "break").

-- 
Gabriel Genellina




More information about the Python-list mailing list