seeking deeper (language theory) reason behind Python design choice

Chris Angelico rosuav at gmail.com
Fri May 11 03:06:42 EDT 2018


On Fri, May 11, 2018 at 4:54 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Thu, May 10, 2018 at 11:45 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> To be honest, I'm having trouble thinking of a good use-case for "while
>> True", now that we have infinite iterators. Most cases of
>>
>>     while True:
>>         x = get_item()
>>         if not x: break
>>         process(x)
>>
>> are better written as:
>>
>>     for x in iterator:
>>         process(x)
>
> x = get_item()
> while True:
>     x = process(x)

More likely:

x = get_item()
while x:
    process(x)
    x = get_item()

which (a) repeats the call to get_item, (b) doesn't support the
'continue' statement, and (c) hides crucial loop iteration information
at the BOTTOM of the loop.

But to make this iterator, you need to separate the while loop's
header from its body. Compare:

while x := get_item():
    process(x)


def get_items():
    while True:
        x = get_item()
        if not x: return
        yield x

for x in get_items():
    process(x)

It hasn't actually gotten rid of the fib of the infinite loop; all
it's done is wrap it up in a function. Yes, that can be of value; but
adding another level of indirection doesn't solve a problem, it just
moves it around.

ChrisA



More information about the Python-list mailing list