seeking deeper (language theory) reason behind Python design choice

Chris Angelico rosuav at gmail.com
Thu May 10 16:07:32 EDT 2018


On Fri, May 11, 2018 at 5:59 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Mikhail V <mikhailwas at gmail.com>:
>
>> On Wed, May 9, 2018 at 8:50 AM, Chris Angelico <rosuav at gmail.com> wrote:
>>> On Wed, May 9, 2018 at 3:36 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>>>> while True:
>>>
>>> Why is it that "while True" is idiomatic Python for a non-infinite
>>> loop? Is it merely because Python currently has no other way to spell
>>> certain loops? Surely it would be more idiomatic to encode the loop's
>>> termination condition in the header, if it were possible.
>>
>> Don't know about 'idiomatic', but the above spelling is exactly what i
>> tend to use lately for almost all loops. It noticeably reduces
>> cognitive load. Though lately more often i prefer "while 1:" so it
>> makes the nodes more lightweight and distinct from the rest lines. And
>> not even official declaration of "idiomatic" as something else will
>> make me switch back.
>
> How about:
>
>    while ...:
>        do_stuff()
>        if done:
>            break
>        do_more_stuff()
>
> where ... is the Ellipsis.
>
> Joking aside, to answer Chris's question, of course you can use a real
> condition with "while". However, you shouldn't force it or try to avoid
> "while True". It turns out "while True" is the most natural choice in
> about half of the while loops.

So if I understand you correctly, you're saying that a real condition
is better, but "while True" is the best option half the time. In other
words, "while True" is the ONLY option half the time, since any other
option would be better.

My point is that creating a way to write more conditions as actual
loop headers is an improvement in Pythonicity, not a worsening of it.
It is not fundamentally Pythonic to write a non-infinite loop as
"while True"; that is a limitation caused by the inability to
represent certain conditions in any better way.

It is NOT idiomatic to use "while True" and then write your condition
just inside the loop.

ChrisA



More information about the Python-list mailing list