PEP 315: Enhanced While Loop

Steven Taschuk staschuk at telusplanet.net
Mon May 5 16:31:46 EDT 2003


Quoth W Isaac Carroll:
  [...]
> * "do" is unclear
> * do-while in other languages doesn't have 2nd suite
> * do-while-while ambiguity
> * unseen "do" changes the meaning of seen "while"
> 
> These are problems which I had not considered when writing the PEP. 

Good!  (Then the process is working.)

  [...]
> * infinite loop with break is a well-known idiom in other languages and
>    is a good way of expressing this behavior
> 
> Experienced programmers are used to writing infinite loops and breaking 
> out of them. However, saying "while True" does not clearly express the 
> purpose and behavior of the loop. Just because it's traditional to write 
> infinite loops does not mean that it's a good way to program.

Of course, with 'while True' and 'if ...: break', usually the loop
is not infinite (barring bugs).  If I understand correctly, you're
saying that 'while True' suggests that the programmer *intends* an
infinite loop, and so is misleading.

If that's right, how about this?

    loop:
        do some stuff
        if should stop now:
            break
        do some other stuff

The 'loop' just says "this is a loop; execution comes back here at
the end of the block".  Unlike 'while True', it does not also
explicitly say "we will continue looping as long as True is true".
(The notion is that the problem is while's mandatory condition,
which adds no information in the case of these so-called infinite
loops.)

Any better in your view?  (I can't tell; I'm too used to looking
for 'if ...: break' after seeing 'while True'.)

> I feel that the use of break is similar to the use of goto in the past. 
> Goto was necessary because of the limited control structures available 
> in early languages, but as for, while, if-else, functions, and other 
> powerful control structures came into use, the goto was no longer 
> necessary and gradually disappeared. If we adopt loop constructs of 
> sufficient power and flexibility, the break statement will also no 
> longer be needed, and will disappear from use.

Imho 'break' and 'continue' together make 'while' a "loop
construct of sufficient power and flexibility".  :)

Incidentally, I'd like to see a concrete example of the kind of
problem which you'd solve by writing a loop with the proposed
syntax.  (Most such cases in my experience are problems involving
a stream of objects to be processed; it would be nice to see
either a different kind of problem for which this syntax is
suited, or a stream-of-objects problem for which it is superior to
approaches using, say, iterators and a for loop.)

  [...]
-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list