[Python-Dev] Assignment expression and coding style: the while True case

Nathaniel Smith njs at pobox.com
Wed Jul 4 19:15:41 EDT 2018


On Wed, Jul 4, 2018 at 3:51 PM, Victor Stinner <vstinner at redhat.com> wrote:
> My question is now: for which "while True" patterns are the assignment
> expression appropriate? There identified different patterns.
>
>
> == Pattern 1, straighforward ==
>
> while True:
>     line = input.readline()
>     if not line:
>         break
>     ...
>
> IMHO here assingment expression is appropriate here. The code remains
> straighfoward to read.
>
> while (line := input.readline()):
>     ...

There are some obvious caveats here – no-one has real experience with
:= yet, so any opinions right now are informed guesswork that will
probably change some if/when we get more experience with it. Also, the
stdlib is a big place, and it seems inevitable that maintainers of
different modules will have different preferences. So I don't think it
makes sense to try to define some Official Universal Rule about when
:= is appropriate and when it isn't.

That said, FWIW, my current feeling is that this simplest case is the
only one where I would use :=; for your other examples I'd stick with
the loop-and-a-half style.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-Dev mailing list