Extension of while syntax

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Dec 13 06:56:31 EST 2014


Nelson Crosby wrote:

> I was thinking a bit about the following pattern:
> 
> value = get_some_value()
> while value in undesired_values:
>     value = get_some_value()
> 
> I've always hated code that looks like this. Partly due to the repetition,
> but partly also due to the fact that without being able to immediately
> recognise this pattern, it isn't very readable.


I agree! There are two fundamental indefinite loop structure:

- loop zero or more times
- loop one or more times

Python has syntax to support the first, namely `while`, but doesn't have
syntax to support the second.

Now it is certainly true that not everything needs to be syntax. You can
easily adjust a `while` loop to behave like a one-or-more loop. One way is
to use a sentinel value that is guaranteed to be in the undesired set:

value = something_undesired
while value in undesired_values:
    value = get_some_value()


Another way is to use an infinite loop and then break out after at least one
cycle:

while True:
    value = get_some_value()
    if value in undesired_values:
        break



Both of these can be good enough. A good programmer should know these
techniques because they can be generalised to "loop and a half":

while True:
    first_half()
    if condition:
        break
    second_half()


and any other semantics you might like. (This suggestions that there is, in
fact, only one *fundamental* indefinite loop: the infinite loop.)

But neither is elegant and neither reads like English pseudo-code. Pascal
has syntax for one-or-more loops, and inspired by that Python might have
had something like this:

repeat:
    <block>
until condition

That however would require two new keywords (repeat and until), and the
benefit is not enough to make it worth breaking all the code that already
uses "repeat" as a variable.


> Python already has one-line syntaxes (e.g. list comprehensions), I was
> wondering what people thought about a similar thing with while. It might
> look something like:
> 
> value = get_some_value() while value in undesired_values()

That is no help at all for the general case where you have a block of code
inside the while loop. It certainly isn't worth having syntax for such a
special case.



-- 
Steven




More information about the Python-list mailing list