The rap against "while True:" loops

Mel mwilson at the-wire.com
Mon Oct 12 10:58:46 EDT 2009


Luis Zarrabeitia wrote:

> On Sunday 11 October 2009 11:56:55 pm Dennis Lee Bieber wrote:
>> In this situation, the middle exit works best -- using
>> non-optimal Python
>>
>> while True:
>> lin = file_object.readline()
>> if not lin: break
>> do something with lin
> 
> Actually, in python, this works even better:
> 
> for lin in iter(file_object.readline, ""):
>     ... do something with lin

And one can do this oneself.  Faced with

while True:
    stuff_required_to_make_the_decision()
    if the_decision():
        break
    other_stuff()


Wrapping the `stuff_required_...` and `the_decision` up into a generator 
would simplify the statement, and if it were done well the code overall 
would probably be better.

	Mel.





More information about the Python-list mailing list