while true: !!!

Delaney, Timothy tdelaney at avaya.com
Wed Dec 20 00:22:51 CET 2000


> > > >The idiom is actually
> > > >
> > > >while 1:
> > > >
> > > > do something
> > > >
> > > > if condition:
> > > > break
> > > >
> > > > do something else
>     [snip]
> > I go well out of my way to avoid this idiom, as I feel you 
> should always
> > have the termination condition at one end of the loop, 
> preferably the top
> 
> I disagree intensely with this stance: I strongly feel that the
> loop-exit condition should be *in the most natural place for it*,
> which is often the top, but not all that rarely elsewhere.
> 
> Anyway, one doesn't have to go 'well' out of one way to hide
> this clean, general loop structure as if it was otherwise --
> one 'status-variable' will suffice, e.g:
> 
> looping = 1
> while looping:
>     do something
>     if condition:
>         looping = 0
>     else:
>         do something else
>
> I think this is *substantially* less readable than the
> clean, natural form:
> 
> while 1:
>     do something
>     if condition: break
>     do something else

I don't usually do this either, as it is actually *worse* unless there is a
very obvious "thing" which the loop should end on.

Instead, I attempt to create a situation where *all* the decision-making is
encapsulated in the condition. This may well mean that I define a class or
function which does something, supplying me with data and a loop exit
condition. Again, the canonical example is reading a file:

maybe_buffered_stream = MaybeBufferedFileInputStream(file_object)

while maybe_buffered_stream.has_unread_contents:
	line = maybe_buffered_stream.readline()

Tim Delaney
Avaya Australia




More information about the Python-list mailing list