The rap against "while True:" loops

Mel mwilson at
Mon Oct 12 16:58:46 CEST 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:
    if the_decision():

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.


More information about the Python-list mailing list